path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
ajax/libs/react-redux/7.1.0-rc.1/react-redux.js
sufuf3/cdnjs
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('redux'), require('react-dom')) : typeof define === 'function' && define.amd ? define(['exports', 'react', 'redux', 'react-dom'], factory) : (global = global || self, factory(global.ReactRedux = {}, global.React, global.Redux, global.ReactDOM)); }(this, function (exports, React, redux, reactDom) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var reactIs_development = createCommonjsModule(function (module, exports) { { (function() { Object.defineProperty(exports, '__esModule', { value: true }); // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf; var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; function isValidElementType(type) { return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE); } /** * Forked from fbjs/warning: * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js * * Only change is we use console.warn instead of console.error, * and do nothing when 'console' is not supported. * This really simplifies the code. * --- * 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 lowPriorityWarning = function () {}; { var printWarning = function (format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.warn(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) {} }; lowPriorityWarning = function (condition, format) { if (format === undefined) { throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } var lowPriorityWarning$1 = lowPriorityWarning; function typeOf(object) { if (typeof object === 'object' && object !== null) { var $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type = object.type; switch (type) { case REACT_ASYNC_MODE_TYPE: case REACT_CONCURRENT_MODE_TYPE: case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: return type; default: var $$typeofType = type && type.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: case REACT_PORTAL_TYPE: return $$typeof; } } return undefined; } // AsyncMode is deprecated along with isAsyncMode var AsyncMode = REACT_ASYNC_MODE_TYPE; var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Lazy = REACT_LAZY_TYPE; var Memo = REACT_MEMO_TYPE; var Portal = REACT_PORTAL_TYPE; var Profiler = REACT_PROFILER_TYPE; var StrictMode = REACT_STRICT_MODE_TYPE; var Suspense = REACT_SUSPENSE_TYPE; var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated function isAsyncMode(object) { { if (!hasWarnedAboutDeprecatedIsAsyncMode) { hasWarnedAboutDeprecatedIsAsyncMode = true; lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.'); } } return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE; } function isConcurrentMode(object) { return typeOf(object) === REACT_CONCURRENT_MODE_TYPE; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isLazy(object) { return typeOf(object) === REACT_LAZY_TYPE; } function isMemo(object) { return typeOf(object) === REACT_MEMO_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } function isSuspense(object) { return typeOf(object) === REACT_SUSPENSE_TYPE; } exports.typeOf = typeOf; exports.AsyncMode = AsyncMode; exports.ConcurrentMode = ConcurrentMode; exports.ContextConsumer = ContextConsumer; exports.ContextProvider = ContextProvider; exports.Element = Element; exports.ForwardRef = ForwardRef; exports.Fragment = Fragment; exports.Lazy = Lazy; exports.Memo = Memo; exports.Portal = Portal; exports.Profiler = Profiler; exports.StrictMode = StrictMode; exports.Suspense = Suspense; exports.isValidElementType = isValidElementType; exports.isAsyncMode = isAsyncMode; exports.isConcurrentMode = isConcurrentMode; exports.isContextConsumer = isContextConsumer; exports.isContextProvider = isContextProvider; exports.isElement = isElement; exports.isForwardRef = isForwardRef; exports.isFragment = isFragment; exports.isLazy = isLazy; exports.isMemo = isMemo; exports.isPortal = isPortal; exports.isProfiler = isProfiler; exports.isStrictMode = isStrictMode; exports.isSuspense = isSuspense; })(); } }); unwrapExports(reactIs_development); var reactIs_development_1 = reactIs_development.typeOf; var reactIs_development_2 = reactIs_development.AsyncMode; var reactIs_development_3 = reactIs_development.ConcurrentMode; var reactIs_development_4 = reactIs_development.ContextConsumer; var reactIs_development_5 = reactIs_development.ContextProvider; var reactIs_development_6 = reactIs_development.Element; var reactIs_development_7 = reactIs_development.ForwardRef; var reactIs_development_8 = reactIs_development.Fragment; var reactIs_development_9 = reactIs_development.Lazy; var reactIs_development_10 = reactIs_development.Memo; var reactIs_development_11 = reactIs_development.Portal; var reactIs_development_12 = reactIs_development.Profiler; var reactIs_development_13 = reactIs_development.StrictMode; var reactIs_development_14 = reactIs_development.Suspense; var reactIs_development_15 = reactIs_development.isValidElementType; var reactIs_development_16 = reactIs_development.isAsyncMode; var reactIs_development_17 = reactIs_development.isConcurrentMode; var reactIs_development_18 = reactIs_development.isContextConsumer; var reactIs_development_19 = reactIs_development.isContextProvider; var reactIs_development_20 = reactIs_development.isElement; var reactIs_development_21 = reactIs_development.isForwardRef; var reactIs_development_22 = reactIs_development.isFragment; var reactIs_development_23 = reactIs_development.isLazy; var reactIs_development_24 = reactIs_development.isMemo; var reactIs_development_25 = reactIs_development.isPortal; var reactIs_development_26 = reactIs_development.isProfiler; var reactIs_development_27 = reactIs_development.isStrictMode; var reactIs_development_28 = reactIs_development.isSuspense; var reactIs = createCommonjsModule(function (module) { { module.exports = reactIs_development; } }); var reactIs_1 = reactIs.isValidElementType; var reactIs_2 = reactIs.isContextConsumer; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; var printWarning = function() {}; { var ReactPropTypesSecret$1 = ReactPropTypesSecret_1; var loggedTypeFailures = {}; var has = Function.call.bind(Object.prototype.hasOwnProperty); printWarning = function(text) { var message = 'Warning: ' + text; 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) {} }; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { { for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' ); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ); } 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 stack = getStack ? getStack() : ''; printWarning( 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') ); } } } } } /** * Resets warning cache when testing. * * @private */ checkPropTypes.resetWarningCache = function() { { loggedTypeFailures = {}; } }; var checkPropTypes_1 = checkPropTypes; var has$1 = Function.call.bind(Object.prototype.hasOwnProperty); var printWarning$1 = function() {}; { printWarning$1 = function(text) { var message = 'Warning: ' + text; 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) {} }; } function emptyFunctionThatReturnsNull() { return null; } var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), elementType: createElementTypeTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker, }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret_1) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package var err = new Error( 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); err.name = 'Invariant Violation'; throw err; } else if (typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { printWarning$1( 'You are manually calling a React.PropTypes validation ' + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunctionThatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createElementTypeTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!reactIs.isValidElementType(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { { if (arguments.length > 1) { printWarning$1( 'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' + 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).' ); } else { printWarning$1('Invalid argument supplied to oneOf, expected an array.'); } } return emptyFunctionThatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues, function replacer(key, value) { var type = getPreciseType(value); if (type === 'symbol') { return String(value); } return value; }); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (has$1(propValue, key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { printWarning$1('Invalid argument supplied to oneOfType, expected an instance of array.'); return emptyFunctionThatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { printWarning$1( 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.' ); return emptyFunctionThatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createStrictShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } // We need to check all keys in case some are required but missing from // props. var allKeys = objectAssign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (!checker) { return new PropTypeError( 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // falsy value can't be a Symbol if (!propValue) { return false; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes_1; ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var propTypes = createCommonjsModule(function (module) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ { var ReactIs = reactIs; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess); } }); var ReactReduxContext = React__default.createContext(null); // Default to a dummy "batch" implementation that just runs the callback function defaultNoopBatch(callback) { callback(); } var batch = defaultNoopBatch; // Allow injecting another batching function later var setBatch = function setBatch(newBatch) { return batch = newBatch; }; // Supply a getter just to skip dealing with ESM bindings var getBatch = function getBatch() { return batch; }; // well as nesting subscriptions of descendant components, so that we can ensure the // ancestor components re-render before descendants var CLEARED = null; var nullListeners = { notify: function notify() {} }; function createListenerCollection() { var batch = getBatch(); // the current/next pattern is copied from redux's createStore code. // TODO: refactor+expose that code to be reusable here? var current = []; var next = []; return { clear: function clear() { next = CLEARED; current = CLEARED; }, notify: function notify() { var listeners = current = next; batch(function () { for (var i = 0; i < listeners.length; i++) { listeners[i](); } }); }, get: function get() { return next; }, subscribe: function subscribe(listener) { var isSubscribed = true; if (next === current) next = current.slice(); next.push(listener); return function unsubscribe() { if (!isSubscribed || current === CLEARED) return; isSubscribed = false; if (next === current) next = current.slice(); next.splice(next.indexOf(listener), 1); }; } }; } var Subscription = /*#__PURE__*/ function () { function Subscription(store, parentSub) { this.store = store; this.parentSub = parentSub; this.unsubscribe = null; this.listeners = nullListeners; this.handleChangeWrapper = this.handleChangeWrapper.bind(this); } var _proto = Subscription.prototype; _proto.addNestedSub = function addNestedSub(listener) { this.trySubscribe(); return this.listeners.subscribe(listener); }; _proto.notifyNestedSubs = function notifyNestedSubs() { this.listeners.notify(); }; _proto.handleChangeWrapper = function handleChangeWrapper() { if (this.onStateChange) { this.onStateChange(); } }; _proto.isSubscribed = function isSubscribed() { return Boolean(this.unsubscribe); }; _proto.trySubscribe = function trySubscribe() { if (!this.unsubscribe) { this.unsubscribe = this.parentSub ? this.parentSub.addNestedSub(this.handleChangeWrapper) : this.store.subscribe(this.handleChangeWrapper); this.listeners = createListenerCollection(); } }; _proto.tryUnsubscribe = function tryUnsubscribe() { if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; this.listeners.clear(); this.listeners = nullListeners; } }; return Subscription; }(); var Provider = /*#__PURE__*/ function (_Component) { _inheritsLoose(Provider, _Component); function Provider(props) { var _this; _this = _Component.call(this, props) || this; var store = props.store; _this.notifySubscribers = _this.notifySubscribers.bind(_assertThisInitialized(_this)); var subscription = new Subscription(store); subscription.onStateChange = _this.notifySubscribers; _this.state = { store: store, subscription: subscription }; _this.previousState = store.getState(); return _this; } var _proto = Provider.prototype; _proto.componentDidMount = function componentDidMount() { this._isMounted = true; this.state.subscription.trySubscribe(); if (this.previousState !== this.props.store.getState()) { this.state.subscription.notifyNestedSubs(); } }; _proto.componentWillUnmount = function componentWillUnmount() { if (this.unsubscribe) this.unsubscribe(); this.state.subscription.tryUnsubscribe(); this._isMounted = false; }; _proto.componentDidUpdate = function componentDidUpdate(prevProps) { if (this.props.store !== prevProps.store) { this.state.subscription.tryUnsubscribe(); var subscription = new Subscription(this.props.store); subscription.onStateChange = this.notifySubscribers; this.setState({ store: this.props.store, subscription: subscription }); } }; _proto.notifySubscribers = function notifySubscribers() { this.state.subscription.notifyNestedSubs(); }; _proto.render = function render() { var Context = this.props.context || ReactReduxContext; return React__default.createElement(Context.Provider, { value: this.state }, this.props.children); }; return Provider; }(React.Component); Provider.propTypes = { store: propTypes.shape({ subscribe: propTypes.func.isRequired, dispatch: propTypes.func.isRequired, getState: propTypes.func.isRequired }), context: propTypes.object, children: propTypes.any }; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var REACT_STATICS = { childContextTypes: true, contextType: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromError: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var FORWARD_REF_STATICS = { '$$typeof': true, render: true, defaultProps: true, displayName: true, propTypes: true }; var MEMO_STATICS = { '$$typeof': true, compare: true, defaultProps: true, displayName: true, propTypes: true, type: true }; var TYPE_STATICS = {}; TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS; function getStatics(component) { if (reactIs.isMemo(component)) { return MEMO_STATICS; } return TYPE_STATICS[component['$$typeof']] || REACT_STATICS; } var defineProperty = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols$1 = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf = Object.getPrototypeOf; var objectPrototype = Object.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components if (objectPrototype) { var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } } var keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols$1) { keys = keys.concat(getOwnPropertySymbols$1(sourceComponent)); } var targetStatics = getStatics(targetComponent); var sourceStatics = getStatics(sourceComponent); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) { var descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) {} } } return targetComponent; } return targetComponent; } var hoistNonReactStatics_cjs = hoistNonReactStatics; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var invariant = function(condition, format, a, b, c, d, e, f) { { 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; } }; var invariant_1 = invariant; var EMPTY_ARRAY = []; var NO_SUBSCRIPTION_ARRAY = [null, null]; var stringifyComponent = function stringifyComponent(Comp) { try { return JSON.stringify(Comp); } catch (err) { return String(Comp); } }; function storeStateUpdatesReducer(state, action) { var updateCount = state[1]; return [action.payload, updateCount + 1]; } var initStateUpdates = function initStateUpdates() { return [null, 0]; }; // React currently throws a warning when using useLayoutEffect on the server. // To get around it, we can conditionally useEffect on the server (no-op) and // useLayoutEffect in the browser. We need useLayoutEffect because we want // `connect` to perform sync updates to a ref to save the latest props after // a render is actually committed to the DOM. var useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? React.useLayoutEffect : React.useEffect; function connectAdvanced( /* selectorFactory is a func that is responsible for returning the selector function used to compute new props from state, props, and dispatch. For example: export default connectAdvanced((dispatch, options) => (state, props) => ({ thing: state.things[props.thingId], saveThing: fields => dispatch(actionCreators.saveThing(props.thingId, fields)), }))(YourComponent) Access to dispatch is provided to the factory so selectorFactories can bind actionCreators outside of their selector as an optimization. Options passed to connectAdvanced are passed to the selectorFactory, along with displayName and WrappedComponent, as the second argument. Note that selectorFactory is responsible for all caching/memoization of inbound and outbound props. Do not use connectAdvanced directly without memoizing results between calls to your selector, otherwise the Connect component will re-render on every state or props change. */ selectorFactory, // options object: _ref) { if (_ref === void 0) { _ref = {}; } var _ref2 = _ref, _ref2$getDisplayName = _ref2.getDisplayName, getDisplayName = _ref2$getDisplayName === void 0 ? function (name) { return "ConnectAdvanced(" + name + ")"; } : _ref2$getDisplayName, _ref2$methodName = _ref2.methodName, methodName = _ref2$methodName === void 0 ? 'connectAdvanced' : _ref2$methodName, _ref2$renderCountProp = _ref2.renderCountProp, renderCountProp = _ref2$renderCountProp === void 0 ? undefined : _ref2$renderCountProp, _ref2$shouldHandleSta = _ref2.shouldHandleStateChanges, shouldHandleStateChanges = _ref2$shouldHandleSta === void 0 ? true : _ref2$shouldHandleSta, _ref2$storeKey = _ref2.storeKey, storeKey = _ref2$storeKey === void 0 ? 'store' : _ref2$storeKey, _ref2$withRef = _ref2.withRef, withRef = _ref2$withRef === void 0 ? false : _ref2$withRef, _ref2$forwardRef = _ref2.forwardRef, forwardRef = _ref2$forwardRef === void 0 ? false : _ref2$forwardRef, _ref2$context = _ref2.context, context = _ref2$context === void 0 ? ReactReduxContext : _ref2$context, connectOptions = _objectWithoutPropertiesLoose(_ref2, ["getDisplayName", "methodName", "renderCountProp", "shouldHandleStateChanges", "storeKey", "withRef", "forwardRef", "context"]); invariant_1(renderCountProp === undefined, "renderCountProp is removed. render counting is built into the latest React Dev Tools profiling extension"); invariant_1(!withRef, 'withRef is removed. To access the wrapped instance, use a ref on the connected component'); var customStoreWarningMessage = 'To use a custom Redux store for specific components, create a custom React context with ' + "React.createContext(), and pass the context object to React Redux's Provider and specific components" + ' like: <Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>. ' + 'You may also pass a {context : MyContext} option to connect'; invariant_1(storeKey === 'store', 'storeKey has been removed and does not do anything. ' + customStoreWarningMessage); var Context = context; return function wrapWithConnect(WrappedComponent) { { invariant_1(reactIs_1(WrappedComponent), "You must pass a component to the function returned by " + (methodName + ". Instead received " + stringifyComponent(WrappedComponent))); } var wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component'; var displayName = getDisplayName(wrappedComponentName); var selectorFactoryOptions = _extends({}, connectOptions, { getDisplayName: getDisplayName, methodName: methodName, renderCountProp: renderCountProp, shouldHandleStateChanges: shouldHandleStateChanges, storeKey: storeKey, displayName: displayName, wrappedComponentName: wrappedComponentName, WrappedComponent: WrappedComponent }); var pure = connectOptions.pure; function createChildSelector(store) { return selectorFactory(store.dispatch, selectorFactoryOptions); } // If we aren't running in "pure" mode, we don't want to memoize values. // To avoid conditionally calling hooks, we fall back to a tiny wrapper // that just executes the given callback immediately. var usePureOnlyMemo = pure ? React.useMemo : function (callback) { return callback(); }; function ConnectFunction(props) { var _useMemo = React.useMemo(function () { // Distinguish between actual "data" props that were passed to the wrapper component, // and values needed to control behavior (forwarded refs, alternate context instances). // To maintain the wrapperProps object reference, memoize this destructuring. var forwardedRef = props.forwardedRef, wrapperProps = _objectWithoutPropertiesLoose(props, ["forwardedRef"]); return [props.context, forwardedRef, wrapperProps]; }, [props]), propsContext = _useMemo[0], forwardedRef = _useMemo[1], wrapperProps = _useMemo[2]; var ContextToUse = React.useMemo(function () { // Users may optionally pass in a custom context instance to use instead of our ReactReduxContext. // Memoize the check that determines which context instance we should use. return propsContext && propsContext.Consumer && reactIs_2(React__default.createElement(propsContext.Consumer, null)) ? propsContext : Context; }, [propsContext, Context]); // Retrieve the store and ancestor subscription via context, if available var contextValue = React.useContext(ContextToUse); // The store _must_ exist as either a prop or in context var didStoreComeFromProps = Boolean(props.store); var didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store); invariant_1(didStoreComeFromProps || didStoreComeFromContext, "Could not find \"store\" in the context of " + ("\"" + displayName + "\". Either wrap the root component in a <Provider>, ") + "or pass a custom React context provider to <Provider> and the corresponding " + ("React context consumer to " + displayName + " in connect options.")); var store = props.store || contextValue.store; var childPropsSelector = React.useMemo(function () { // The child props selector needs the store reference as an input. // Re-create this selector whenever the store changes. return createChildSelector(store); }, [store]); var _useMemo2 = React.useMemo(function () { if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY; // This Subscription's source should match where store came from: props vs. context. A component // connected to the store via props shouldn't use subscription from context, or vice versa. var subscription = new Subscription(store, didStoreComeFromProps ? null : contextValue.subscription); // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in // the middle of the notification loop, where `subscription` will then be null. This can // probably be avoided if Subscription's listeners logic is changed to not call listeners // that have been unsubscribed in the middle of the notification loop. var notifyNestedSubs = subscription.notifyNestedSubs.bind(subscription); return [subscription, notifyNestedSubs]; }, [store, didStoreComeFromProps, contextValue]), subscription = _useMemo2[0], notifyNestedSubs = _useMemo2[1]; // Determine what {store, subscription} value should be put into nested context, if necessary, // and memoize that value to avoid unnecessary context updates. var overriddenContextValue = React.useMemo(function () { if (didStoreComeFromProps) { // This component is directly subscribed to a store from props. // We don't want descendants reading from this store - pass down whatever // the existing context value is from the nearest connected ancestor. return contextValue; } // Otherwise, put this component's subscription instance into context, so that // connected descendants won't update until after this component is done return _extends({}, contextValue, { subscription: subscription }); }, [didStoreComeFromProps, contextValue, subscription]); // We need to force this wrapper component to re-render whenever a Redux store update // causes a change to the calculated child component props (or we caught an error in mapState) var _useReducer = React.useReducer(storeStateUpdatesReducer, EMPTY_ARRAY, initStateUpdates), _useReducer$ = _useReducer[0], previousStateUpdateResult = _useReducer$[0], forceComponentUpdateDispatch = _useReducer[1]; // Propagate any mapState/mapDispatch errors upwards if (previousStateUpdateResult && previousStateUpdateResult.error) { throw previousStateUpdateResult.error; } // Set up refs to coordinate values between the subscription effect and the render logic var lastChildProps = React.useRef(); var lastWrapperProps = React.useRef(wrapperProps); var childPropsFromStoreUpdate = React.useRef(); var renderIsScheduled = React.useRef(false); var actualChildProps = usePureOnlyMemo(function () { // Tricky logic here: // - This render may have been triggered by a Redux store update that produced new child props // - However, we may have gotten new wrapper props after that // If we have new child props, and the same wrapper props, we know we should use the new child props as-is. // But, if we have new wrapper props, those might change the child props, so we have to recalculate things. // So, we'll use the child props from store update only if the wrapper props are the same as last time. if (childPropsFromStoreUpdate.current && wrapperProps === lastWrapperProps.current) { return childPropsFromStoreUpdate.current; } // TODO We're reading the store directly in render() here. Bad idea? // This will likely cause Bad Things (TM) to happen in Concurrent Mode. // Note that we do this because on renders _not_ caused by store updates, we need the latest store state // to determine what the child props should be. return childPropsSelector(store.getState(), wrapperProps); }, [store, previousStateUpdateResult, wrapperProps]); // We need this to execute synchronously every time we re-render. However, React warns // about useLayoutEffect in SSR, so we try to detect environment and fall back to // just useEffect instead to avoid the warning, since neither will run anyway. useIsomorphicLayoutEffect(function () { // We want to capture the wrapper props and child props we used for later comparisons lastWrapperProps.current = wrapperProps; lastChildProps.current = actualChildProps; renderIsScheduled.current = false; // If the render was from a store update, clear out that reference and cascade the subscriber update if (childPropsFromStoreUpdate.current) { childPropsFromStoreUpdate.current = null; notifyNestedSubs(); } }); // Our re-subscribe logic only runs when the store/subscription setup changes useIsomorphicLayoutEffect(function () { // If we're not subscribed to the store, nothing to do here if (!shouldHandleStateChanges) return; // Capture values for checking if and when this component unmounts var didUnsubscribe = false; var lastThrownError = null; // We'll run this callback every time a store subscription update propagates to this component var checkForUpdates = function checkForUpdates() { if (didUnsubscribe) { // Don't run stale listeners. // Redux doesn't guarantee unsubscriptions happen until next dispatch. return; } var latestStoreState = store.getState(); var newChildProps, error; try { // Actually run the selector with the most recent store state and wrapper props // to determine what the child props should be newChildProps = childPropsSelector(latestStoreState, lastWrapperProps.current); } catch (e) { error = e; lastThrownError = e; } if (!error) { lastThrownError = null; } // If the child props haven't changed, nothing to do here - cascade the subscription update if (newChildProps === lastChildProps.current) { if (!renderIsScheduled.current) { notifyNestedSubs(); } } else { // Save references to the new child props. Note that we track the "child props from store update" // as a ref instead of a useState/useReducer because we need a way to determine if that value has // been processed. If this went into useState/useReducer, we couldn't clear out the value without // forcing another re-render, which we don't want. lastChildProps.current = newChildProps; childPropsFromStoreUpdate.current = newChildProps; renderIsScheduled.current = true; // If the child props _did_ change (or we caught an error), this wrapper component needs to re-render forceComponentUpdateDispatch({ type: 'STORE_UPDATED', payload: { latestStoreState: latestStoreState, error: error } }); } }; // Actually subscribe to the nearest connected ancestor (or store) subscription.onStateChange = checkForUpdates; subscription.trySubscribe(); // Pull data from the store after first render in case the store has // changed since we began. checkForUpdates(); var unsubscribeWrapper = function unsubscribeWrapper() { didUnsubscribe = true; subscription.tryUnsubscribe(); if (lastThrownError) { // It's possible that we caught an error due to a bad mapState function, but the // parent re-rendered without this component and we're about to unmount. // This shouldn't happen as long as we do top-down subscriptions correctly, but // if we ever do those wrong, this throw will surface the error in our tests. // In that case, throw the error from here so it doesn't get lost. throw lastThrownError; } }; return unsubscribeWrapper; }, [store, subscription, childPropsSelector]); // Now that all that's done, we can finally try to actually render the child component. // We memoize the elements for the rendered child component as an optimization. var renderedWrappedComponent = React.useMemo(function () { return React__default.createElement(WrappedComponent, _extends({}, actualChildProps, { ref: forwardedRef })); }, [forwardedRef, WrappedComponent, actualChildProps]); // If React sees the exact same element reference as last time, it bails out of re-rendering // that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate. var renderedChild = React.useMemo(function () { if (shouldHandleStateChanges) { // If this component is subscribed to store updates, we need to pass its own // subscription instance down to our descendants. That means rendering the same // Context instance, and putting a different value into the context. return React__default.createElement(ContextToUse.Provider, { value: overriddenContextValue }, renderedWrappedComponent); } return renderedWrappedComponent; }, [ContextToUse, renderedWrappedComponent, overriddenContextValue]); return renderedChild; } // If we're in "pure" mode, ensure our wrapper component only re-renders when incoming props have changed. var Connect = pure ? React__default.memo(ConnectFunction) : ConnectFunction; Connect.WrappedComponent = WrappedComponent; Connect.displayName = displayName; if (forwardRef) { var forwarded = React__default.forwardRef(function forwardConnectRef(props, ref) { return React__default.createElement(Connect, _extends({}, props, { forwardedRef: ref })); }); forwarded.displayName = displayName; forwarded.WrappedComponent = WrappedComponent; return hoistNonReactStatics_cjs(forwarded, WrappedComponent); } return hoistNonReactStatics_cjs(Connect, WrappedComponent); }; } var hasOwn = Object.prototype.hasOwnProperty; function is(x, y) { if (x === y) { return x !== 0 || y !== 0 || 1 / x === 1 / y; } else { return x !== x && y !== y; } } function shallowEqual(objA, objB) { if (is(objA, objB)) return true; if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) return false; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } /** * @param {any} obj The object to inspect. * @returns {boolean} True if the argument appears to be a plain object. */ function isPlainObject(obj) { if (typeof obj !== 'object' || obj === null) return false; var proto = Object.getPrototypeOf(obj); if (proto === null) return true; var baseProto = proto; while (Object.getPrototypeOf(baseProto) !== null) { baseProto = Object.getPrototypeOf(baseProto); } return proto === baseProto; } /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } function verifyPlainObject(value, displayName, methodName) { if (!isPlainObject(value)) { warning(methodName + "() in " + displayName + " must return a plain object. Instead received " + value + "."); } } function wrapMapToPropsConstant(getConstant) { return function initConstantSelector(dispatch, options) { var constant = getConstant(dispatch, options); function constantSelector() { return constant; } constantSelector.dependsOnOwnProps = false; return constantSelector; }; } // dependsOnOwnProps is used by createMapToPropsProxy to determine whether to pass props as args // to the mapToProps function being wrapped. It is also used by makePurePropsSelector to determine // whether mapToProps needs to be invoked when props have changed. // // A length of one signals that mapToProps does not depend on props from the parent component. // A length of zero is assumed to mean mapToProps is getting args via arguments or ...args and // therefore not reporting its length accurately.. function getDependsOnOwnProps(mapToProps) { return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1; } // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction, // this function wraps mapToProps in a proxy function which does several things: // // * Detects whether the mapToProps function being called depends on props, which // is used by selectorFactory to decide if it should reinvoke on props changes. // // * On first call, handles mapToProps if returns another function, and treats that // new function as the true mapToProps for subsequent calls. // // * On first call, verifies the first result is a plain object, in order to warn // the developer that their mapToProps function is not returning a valid result. // function wrapMapToPropsFunc(mapToProps, methodName) { return function initProxySelector(dispatch, _ref) { var displayName = _ref.displayName; var proxy = function mapToPropsProxy(stateOrDispatch, ownProps) { return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch); }; // allow detectFactoryAndVerify to get ownProps proxy.dependsOnOwnProps = true; proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) { proxy.mapToProps = mapToProps; proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps); var props = proxy(stateOrDispatch, ownProps); if (typeof props === 'function') { proxy.mapToProps = props; proxy.dependsOnOwnProps = getDependsOnOwnProps(props); props = proxy(stateOrDispatch, ownProps); } verifyPlainObject(props, displayName, methodName); return props; }; return proxy; }; } function whenMapDispatchToPropsIsFunction(mapDispatchToProps) { return typeof mapDispatchToProps === 'function' ? wrapMapToPropsFunc(mapDispatchToProps, 'mapDispatchToProps') : undefined; } function whenMapDispatchToPropsIsMissing(mapDispatchToProps) { return !mapDispatchToProps ? wrapMapToPropsConstant(function (dispatch) { return { dispatch: dispatch }; }) : undefined; } function whenMapDispatchToPropsIsObject(mapDispatchToProps) { return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? wrapMapToPropsConstant(function (dispatch) { return redux.bindActionCreators(mapDispatchToProps, dispatch); }) : undefined; } var defaultMapDispatchToPropsFactories = [whenMapDispatchToPropsIsFunction, whenMapDispatchToPropsIsMissing, whenMapDispatchToPropsIsObject]; function whenMapStateToPropsIsFunction(mapStateToProps) { return typeof mapStateToProps === 'function' ? wrapMapToPropsFunc(mapStateToProps, 'mapStateToProps') : undefined; } function whenMapStateToPropsIsMissing(mapStateToProps) { return !mapStateToProps ? wrapMapToPropsConstant(function () { return {}; }) : undefined; } var defaultMapStateToPropsFactories = [whenMapStateToPropsIsFunction, whenMapStateToPropsIsMissing]; function defaultMergeProps(stateProps, dispatchProps, ownProps) { return _extends({}, ownProps, stateProps, dispatchProps); } function wrapMergePropsFunc(mergeProps) { return function initMergePropsProxy(dispatch, _ref) { var displayName = _ref.displayName, pure = _ref.pure, areMergedPropsEqual = _ref.areMergedPropsEqual; var hasRunOnce = false; var mergedProps; return function mergePropsProxy(stateProps, dispatchProps, ownProps) { var nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps); if (hasRunOnce) { if (!pure || !areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps; } else { hasRunOnce = true; mergedProps = nextMergedProps; verifyPlainObject(mergedProps, displayName, 'mergeProps'); } return mergedProps; }; }; } function whenMergePropsIsFunction(mergeProps) { return typeof mergeProps === 'function' ? wrapMergePropsFunc(mergeProps) : undefined; } function whenMergePropsIsOmitted(mergeProps) { return !mergeProps ? function () { return defaultMergeProps; } : undefined; } var defaultMergePropsFactories = [whenMergePropsIsFunction, whenMergePropsIsOmitted]; function verify(selector, methodName, displayName) { if (!selector) { throw new Error("Unexpected value for " + methodName + " in " + displayName + "."); } else if (methodName === 'mapStateToProps' || methodName === 'mapDispatchToProps') { if (!selector.hasOwnProperty('dependsOnOwnProps')) { warning("The selector for " + methodName + " of " + displayName + " did not specify a value for dependsOnOwnProps."); } } } function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, displayName) { verify(mapStateToProps, 'mapStateToProps', displayName); verify(mapDispatchToProps, 'mapDispatchToProps', displayName); verify(mergeProps, 'mergeProps', displayName); } function impureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch) { return function impureFinalPropsSelector(state, ownProps) { return mergeProps(mapStateToProps(state, ownProps), mapDispatchToProps(dispatch, ownProps), ownProps); }; } function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, _ref) { var areStatesEqual = _ref.areStatesEqual, areOwnPropsEqual = _ref.areOwnPropsEqual, areStatePropsEqual = _ref.areStatePropsEqual; var hasRunAtLeastOnce = false; var state; var ownProps; var stateProps; var dispatchProps; var mergedProps; function handleFirstCall(firstState, firstOwnProps) { state = firstState; ownProps = firstOwnProps; stateProps = mapStateToProps(state, ownProps); dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); hasRunAtLeastOnce = true; return mergedProps; } function handleNewPropsAndNewState() { stateProps = mapStateToProps(state, ownProps); if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleNewProps() { if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps); if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleNewState() { var nextStateProps = mapStateToProps(state, ownProps); var statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps); stateProps = nextStateProps; if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleSubsequentCalls(nextState, nextOwnProps) { var propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps); var stateChanged = !areStatesEqual(nextState, state); state = nextState; ownProps = nextOwnProps; if (propsChanged && stateChanged) return handleNewPropsAndNewState(); if (propsChanged) return handleNewProps(); if (stateChanged) return handleNewState(); return mergedProps; } return function pureFinalPropsSelector(nextState, nextOwnProps) { return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps); }; } // TODO: Add more comments // If pure is true, the selector returned by selectorFactory will memoize its results, // allowing connectAdvanced's shouldComponentUpdate to return false if final // props have not changed. If false, the selector will always return a new // object and shouldComponentUpdate will always return true. function finalPropsSelectorFactory(dispatch, _ref2) { var initMapStateToProps = _ref2.initMapStateToProps, initMapDispatchToProps = _ref2.initMapDispatchToProps, initMergeProps = _ref2.initMergeProps, options = _objectWithoutPropertiesLoose(_ref2, ["initMapStateToProps", "initMapDispatchToProps", "initMergeProps"]); var mapStateToProps = initMapStateToProps(dispatch, options); var mapDispatchToProps = initMapDispatchToProps(dispatch, options); var mergeProps = initMergeProps(dispatch, options); { verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, options.displayName); } var selectorFactory = options.pure ? pureFinalPropsSelectorFactory : impureFinalPropsSelectorFactory; return selectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options); } /* connect is a facade over connectAdvanced. It turns its args into a compatible selectorFactory, which has the signature: (dispatch, options) => (nextState, nextOwnProps) => nextFinalProps connect passes its args to connectAdvanced as options, which will in turn pass them to selectorFactory each time a Connect component instance is instantiated or hot reloaded. selectorFactory returns a final props selector from its mapStateToProps, mapStateToPropsFactories, mapDispatchToProps, mapDispatchToPropsFactories, mergeProps, mergePropsFactories, and pure args. The resulting final props selector is called by the Connect component instance whenever it receives new props or store state. */ function match(arg, factories, name) { for (var i = factories.length - 1; i >= 0; i--) { var result = factories[i](arg); if (result) return result; } return function (dispatch, options) { throw new Error("Invalid value of type " + typeof arg + " for " + name + " argument when connecting component " + options.wrappedComponentName + "."); }; } function strictEqual(a, b) { return a === b; } // createConnect with default args builds the 'official' connect behavior. Calling it with // different options opens up some testing and extensibility scenarios function createConnect(_temp) { var _ref = _temp === void 0 ? {} : _temp, _ref$connectHOC = _ref.connectHOC, connectHOC = _ref$connectHOC === void 0 ? connectAdvanced : _ref$connectHOC, _ref$mapStateToPropsF = _ref.mapStateToPropsFactories, mapStateToPropsFactories = _ref$mapStateToPropsF === void 0 ? defaultMapStateToPropsFactories : _ref$mapStateToPropsF, _ref$mapDispatchToPro = _ref.mapDispatchToPropsFactories, mapDispatchToPropsFactories = _ref$mapDispatchToPro === void 0 ? defaultMapDispatchToPropsFactories : _ref$mapDispatchToPro, _ref$mergePropsFactor = _ref.mergePropsFactories, mergePropsFactories = _ref$mergePropsFactor === void 0 ? defaultMergePropsFactories : _ref$mergePropsFactor, _ref$selectorFactory = _ref.selectorFactory, selectorFactory = _ref$selectorFactory === void 0 ? finalPropsSelectorFactory : _ref$selectorFactory; return function connect(mapStateToProps, mapDispatchToProps, mergeProps, _ref2) { if (_ref2 === void 0) { _ref2 = {}; } var _ref3 = _ref2, _ref3$pure = _ref3.pure, pure = _ref3$pure === void 0 ? true : _ref3$pure, _ref3$areStatesEqual = _ref3.areStatesEqual, areStatesEqual = _ref3$areStatesEqual === void 0 ? strictEqual : _ref3$areStatesEqual, _ref3$areOwnPropsEqua = _ref3.areOwnPropsEqual, areOwnPropsEqual = _ref3$areOwnPropsEqua === void 0 ? shallowEqual : _ref3$areOwnPropsEqua, _ref3$areStatePropsEq = _ref3.areStatePropsEqual, areStatePropsEqual = _ref3$areStatePropsEq === void 0 ? shallowEqual : _ref3$areStatePropsEq, _ref3$areMergedPropsE = _ref3.areMergedPropsEqual, areMergedPropsEqual = _ref3$areMergedPropsE === void 0 ? shallowEqual : _ref3$areMergedPropsE, extraOptions = _objectWithoutPropertiesLoose(_ref3, ["pure", "areStatesEqual", "areOwnPropsEqual", "areStatePropsEqual", "areMergedPropsEqual"]); var initMapStateToProps = match(mapStateToProps, mapStateToPropsFactories, 'mapStateToProps'); var initMapDispatchToProps = match(mapDispatchToProps, mapDispatchToPropsFactories, 'mapDispatchToProps'); var initMergeProps = match(mergeProps, mergePropsFactories, 'mergeProps'); return connectHOC(selectorFactory, _extends({ // used in error messages methodName: 'connect', // used to compute Connect's displayName from the wrapped component's displayName. getDisplayName: function getDisplayName(name) { return "Connect(" + name + ")"; }, // if mapStateToProps is falsy, the Connect component doesn't subscribe to store state changes shouldHandleStateChanges: Boolean(mapStateToProps), // passed through to selectorFactory initMapStateToProps: initMapStateToProps, initMapDispatchToProps: initMapDispatchToProps, initMergeProps: initMergeProps, pure: pure, areStatesEqual: areStatesEqual, areOwnPropsEqual: areOwnPropsEqual, areStatePropsEqual: areStatePropsEqual, areMergedPropsEqual: areMergedPropsEqual }, extraOptions)); }; } var connect = createConnect(); /** * A hook to access the value of the `ReactReduxContext`. This is a low-level * hook that you should usually not need to call directly. * * @returns {any} the value of the `ReactReduxContext` * * @example * * import React from 'react' * import { useReduxContext } from 'react-redux' * * export const CounterComponent = ({ value }) => { * const { store } = useReduxContext() * return <div>{store.getState()}</div> * } */ function useReduxContext() { var contextValue = React.useContext(ReactReduxContext); invariant_1(contextValue, 'could not find react-redux context value; please ensure the component is wrapped in a <Provider>'); return contextValue; } /** * A hook to access the redux store. * * @returns {any} the redux store * * @example * * import React from 'react' * import { useStore } from 'react-redux' * * export const ExampleComponent = () => { * const store = useStore() * return <div>{store.getState()}</div> * } */ function useStore() { var _useReduxContext = useReduxContext(), store = _useReduxContext.store; return store; } /** * A hook to access the redux `dispatch` function. Note that in most cases where you * might want to use this hook it is recommended to use `useActions` instead to bind * action creators to the `dispatch` function. * * @returns {any|function} redux store's `dispatch` function * * @example * * import React, { useCallback } from 'react' * import { useReduxDispatch } from 'react-redux' * * export const CounterComponent = ({ value }) => { * const dispatch = useDispatch() * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), []) * return ( * <div> * <span>{value}</span> * <button onClick={increaseCounter}>Increase counter</button> * </div> * ) * } */ function useDispatch() { var store = useStore(); return store.dispatch; } // To get around it, we can conditionally useEffect on the server (no-op) and // useLayoutEffect in the browser. We need useLayoutEffect to ensure the store // subscription callback always has the selector from the latest render commit // available, otherwise a store update may happen between render and the effect, // which may cause missed updates; we also must ensure the store subscription // is created synchronously, otherwise a store update may occur before the // subscription is created and an inconsistent state may be observed var useIsomorphicLayoutEffect$1 = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect; var refEquality = function refEquality(a, b) { return a === b; }; /** * A hook to access the redux store's state. This hook takes a selector function * as an argument. The selector is called with the store state. * * This hook takes an optional equality comparison function as the second parameter * that allows you to customize the way the selected state is compared to determine * whether the component needs to be re-rendered. * * @param {Function} selector the selector function * @param {Function=} equalityFn the function that will be used to determine equality * * @returns {any} the selected state * * @example * * import React from 'react' * import { useSelector } from 'react-redux' * * export const CounterComponent = () => { * const counter = useSelector(state => state.counter) * return <div>{counter}</div> * } */ function useSelector(selector, equalityFn) { if (equalityFn === void 0) { equalityFn = refEquality; } invariant_1(selector, "You must pass a selector to useSelectors"); var _useReduxContext = useReduxContext(), store = _useReduxContext.store, contextSub = _useReduxContext.subscription; var _useReducer = React.useReducer(function (s) { return s + 1; }, 0), forceRender = _useReducer[1]; var subscription = React.useMemo(function () { return new Subscription(store, contextSub); }, [store, contextSub]); var latestSubscriptionCallbackError = React.useRef(); var latestSelector = React.useRef(); var latestSelectedState = React.useRef(); var selectedState; try { if (selector !== latestSelector.current || latestSubscriptionCallbackError.current) { selectedState = selector(store.getState()); } else { selectedState = latestSelectedState.current; } } catch (err) { var errorMessage = "An error occured while selecting the store state: " + err.message + "."; if (latestSubscriptionCallbackError.current) { errorMessage += "\nThe error may be correlated with this previous error:\n" + latestSubscriptionCallbackError.current.stack + "\n\nOriginal stack trace:"; } throw new Error(errorMessage); } useIsomorphicLayoutEffect$1(function () { latestSelector.current = selector; latestSelectedState.current = selectedState; latestSubscriptionCallbackError.current = undefined; }); useIsomorphicLayoutEffect$1(function () { function checkForUpdates() { try { var newSelectedState = latestSelector.current(store.getState()); if (equalityFn(newSelectedState, latestSelectedState.current)) { return; } latestSelectedState.current = newSelectedState; } catch (err) { // we ignore all errors here, since when the component // is re-rendered, the selectors are called again, and // will throw again, if neither props nor store state // changed latestSubscriptionCallbackError.current = err; } forceRender({}); } subscription.onStateChange = checkForUpdates; subscription.trySubscribe(); checkForUpdates(); return function () { return subscription.tryUnsubscribe(); }; }, [store, subscription]); return selectedState; } /* eslint-disable import/no-unresolved */ setBatch(reactDom.unstable_batchedUpdates); Object.defineProperty(exports, 'batch', { enumerable: true, get: function () { return reactDom.unstable_batchedUpdates; } }); exports.Provider = Provider; exports.ReactReduxContext = ReactReduxContext; exports.connect = connect; exports.connectAdvanced = connectAdvanced; exports.shallowEqual = shallowEqual; exports.useDispatch = useDispatch; exports.useSelector = useSelector; exports.useStore = useStore; Object.defineProperty(exports, '__esModule', { value: true }); }));
app/components/Collaps/index.js
andyzeli/Bil
import Collapsible from 'react-collapsible'; import React from 'react'; import PropTypes from 'prop-types'; import { createStructuredSelector } from 'reselect'; import {makeSelectEncounters} from 'containers/App/selectors'; import { connect } from 'react-redux'; import Chev from '../Chev'; import SCol from './SCol'; import Table from '../Table'; import TableItem from '../TableItem'; import TableHeading from '../TableHeading'; import TableRow from '../TableRow'; class Collaps extends React.Component { render(){ const {foo} = this.props; return( <SCol trigger="View Past EOBs"> <div style={{padding: '10px', border: '1px solid grey', marginLeft: '10px'}}> <Table style={{paddingLeft:'2px', margin: '0 0 0 0', tableLayout: 'fixed'}}> <TableRow> <TableHeading> Date</TableHeading> <TableHeading>Service</TableHeading> <TableHeading>Charge</TableHeading> <TableHeading>Allowed</TableHeading> <TableHeading>Paid</TableHeading> <TableHeading>Patient Resp</TableHeading> </TableRow> <TableRow> <TableItem>1.1.2018</TableItem> <TableItem>99204</TableItem> <TableItem>$235</TableItem> <TableItem>$130</TableItem> <TableItem>$100</TableItem> <TableItem>$30</TableItem> </TableRow> <TableRow> <TableItem>1.1.2018</TableItem> <TableItem>93799</TableItem> <TableItem>$135</TableItem> <TableItem>$80</TableItem> <TableItem>$80</TableItem> <TableItem>$0</TableItem> </TableRow> </Table> </div> </SCol> ) } } Collaps.propTypes = { trigger: PropTypes.string, } const mapStateToProps = createStructuredSelector({ eobs: makeSelectEncounters(), }) export default connect(mapStateToProps)(Collaps);
examples/react-refetch/src/index.js
gaearon/react-hot-loader
import React from 'react'; import { render } from 'react-dom'; import App from './App'; const root = document.createElement('div'); document.body.appendChild(root); render(<App />, root);
src/view/error/index.js
fishmankkk/mircowater2.0
import React from 'react' import styles from './index.less' import img404 from '../../public/images/404.gif' const Error = () => (<div className="content-inner"> <div className={styles.error}> <img src={img404} alt={'logo'} /> </div> </div>) export default Error
Examples/UIExplorer/NavigatorIOSColorsExample.js
fengshao0907/react-native
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; var React = require('react-native'); var { NavigatorIOS, StatusBarIOS, StyleSheet, Text, View } = React; var EmptyPage = React.createClass({ render: function() { return ( <View style={styles.emptyPage}> <Text style={styles.emptyPageText}> {this.props.text} </Text> </View> ); }, }); var NavigatorIOSColors = React.createClass({ statics: { title: '<NavigatorIOS> - Custom', description: 'iOS navigation with custom nav bar colors', }, render: function() { // Set StatusBar with light contents to get better contrast StatusBarIOS.setStyle('light-content'); return ( <NavigatorIOS style={styles.container} initialRoute={{ component: EmptyPage, title: '<NavigatorIOS>', rightButtonTitle: 'Done', onRightButtonPress: () => { StatusBarIOS.setStyle('default'); this.props.onExampleExit(); }, passProps: { text: 'The nav bar has custom colors with tintColor, ' + 'barTintColor and titleTextColor props.', }, }} tintColor="#FFFFFF" barTintColor="#183E63" titleTextColor="#FFFFFF" translucent="true" /> ); }, }); var styles = StyleSheet.create({ container: { flex: 1, }, emptyPage: { flex: 1, paddingTop: 64, }, emptyPageText: { margin: 10, }, }); NavigatorIOSColors.external = true; module.exports = NavigatorIOSColors;
app/javascript/mastodon/components/skeleton.js
theoria24/mastodon
import React from 'react'; import PropTypes from 'prop-types'; const Skeleton = ({ width, height }) => <span className='skeleton' style={{ width, height }}>&zwnj;</span>; Skeleton.propTypes = { width: PropTypes.number, height: PropTypes.number, }; export default Skeleton;
node_modules/grunt/node_modules/js-yaml/node_modules/argparse/node_modules/underscore.string/test/test_underscore/vendor/jquery.js
keithhackbarth/distance.io
/*! * jQuery JavaScript Library v1.7.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Wed Mar 21 12:46:34 2012 -0700 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? 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 = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context ? context.ownerDocument || context : document ); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.7.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.add( 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( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { 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 ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).off( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery.Callbacks( "once memory" ); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, 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[ 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 && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // 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 ) { if ( typeof data !== "string" || !data ) { return null; } var xml, tmp; 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 && 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.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array, i ) { var len; if ( array ) { if ( indexOf ) { return indexOf.call( array, elem, i ); } len = array.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && array[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var 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 ) { if ( typeof context === "string" ) { var 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 var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to 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(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function 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; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); // String to Object flags format cache var flagsCache = {}; // Convert String-formatted flags into Object-formatted ones and store in cache function createFlags( flags ) { var object = flagsCache[ flags ] = {}, i, length; flags = flags.split( /\s+/ ); for ( i = 0, length = flags.length; i < length; i++ ) { object[ flags[i] ] = true; } return object; } /* * Create a callback list using the following parameters: * * flags: an optional list of space-separated flags that will change how * the callback list behaves * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible flags: * * 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( flags ) { // Convert flags from String-formatted to Object-formatted // (we check in cache first) flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; var // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = [], // 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, // Add one or several callbacks to the list add = function( args ) { var i, length, elem, type, actual; for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { // Inspect recursively add( elem ); } else if ( type === "function" ) { // Add if not in unique mode and callback is not in if ( !flags.unique || !self.has( elem ) ) { list.push( elem ); } } } }, // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; fired = true; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; } } firing = false; if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { self.disable(); } else { list = []; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { var length = list.length; add( 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, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { firingStart = length; fire( memory[ 0 ], memory[ 1 ] ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { var args = arguments, argIndex = 0, argLength = args.length; for ( ; argIndex < argLength ; argIndex++ ) { for ( var i = 0; i < list.length; i++ ) { if ( args[ argIndex ] === list[ i ] ) { // Handle firingIndex and firingLength if ( firing ) { if ( i <= firingLength ) { firingLength--; if ( i <= firingIndex ) { firingIndex--; } } } // Remove the element list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique ) { break; } } } } } return this; }, // Control if a given callback is in the list has: function( fn ) { if ( list ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { if ( fn === list[ i ] ) { return true; } } } return false; }, // 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 || memory === true ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { fire( context, 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; }; var // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ Deferred: function( func ) { var doneList = jQuery.Callbacks( "once memory" ), failList = jQuery.Callbacks( "once memory" ), progressList = jQuery.Callbacks( "memory" ), state = "pending", lists = { resolve: doneList, reject: failList, notify: progressList }, promise = { done: doneList.add, fail: failList.add, progress: progressList.add, state: function() { return state; }, // Deprecated isResolved: doneList.fired, isRejected: failList.fired, then: function( doneCallbacks, failCallbacks, progressCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); return this; }, always: function() { deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); return this; }, pipe: function( fnDone, fnFail, fnProgress ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ], progress: [ fnProgress, "notify" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { obj = promise; } else { for ( var key in promise ) { obj[ key ] = promise[ key ]; } } return obj; } }, deferred = promise.promise({}), key; for ( key in lists ) { deferred[ key ] = lists[ key ].fire; deferred[ key + "With" ] = lists[ key ].fireWith; } // Handle state deferred.done( function() { state = "resolved"; }, failList.disable, progressList.lock ).fail( function() { state = "rejected"; }, doneList.disable, progressList.lock ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( firstParam ) { var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, pValues = new Array( length ), count = length, pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(), promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { deferred.resolveWith( deferred, args ); } }; } function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; deferred.notifyWith( promise, pValues ); }; } if ( length > 1 ) { for ( ; i < length; i++ ) { if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return promise; } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, tds, events, eventName, i, isSupported, div = document.createElement( "div" ), documentElement = document.documentElement; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // 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>", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, pixelMargin: true }; // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); // 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", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // 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: 1, change: 1, focusin: 1 }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } fragment.removeChild( div ); // Null elements to avoid leaks in IE fragment = select = opt = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, paddingMarginBorderVisibility, paddingMarginBorder, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; paddingMarginBorder = "padding:0;margin:0;border:"; positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" + "<table " + style + "' cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; 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 style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); 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 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 if ( window.getComputedStyle ) { div.innerHTML = ""; marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.style.width = "2px"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } 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.width = div.style.padding = "1px"; div.style.border = 0; div.style.overflow = "hidden"; div.style.display = "inline"; div.style.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 style='width:5px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); } div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; div.innerHTML = html; outer = div.firstChild; inner = outer.firstChild; td = outer.nextSibling.firstChild.firstChild; offsetSupport = { doesNotAddBorder: ( inner.offsetTop !== 5 ), doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) }; inner.style.position = "fixed"; inner.style.top = "20px"; // safari subtracts parent border width here which is 5px offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); inner.style.position = inner.style.top = ""; outer.style.overflow = "hidden"; outer.style.position = "relative"; offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); if ( window.getComputedStyle ) { div.style.marginTop = "1%"; support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; } if ( typeof container.style.zoom !== "undefined" ) { container.style.zoom = 1; } body.removeChild( container ); marginDiv = div = container = null; jQuery.extend( support, offsetSupport ); }); return support; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var privateCache, 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, isEvents = name === "events"; // 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] || (!isEvents && !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.uuid; } 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 ); } } privateCache = 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; } // Users should not attempt to inspect the internal events object using jQuery.data, // it is undocumented and subject to change. But does anyone listen? No. if ( isEvents && !thisCache[ name ] ) { return privateCache.events; } // 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, // Reference to internal data cache key internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ internalKey ] : internalKey; // 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; } } // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the cache and need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var 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-" ) === 0 ) { 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 : jQuery.isNumeric( 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 ) { for ( var name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery._data( elem, deferDataKey ); if ( defer && ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery._data( elem, queueDataKey ) && !jQuery._data( elem, markDataKey ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.fire(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = ( type || "fx" ) + "mark"; jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); if ( count ) { jQuery._data( elem, key, count ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { var q; if ( elem ) { type = ( type || "fx" ) + "queue"; q = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), hooks = {}; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } jQuery._data( elem, type + ".run", hooks ); fn.call( elem, function() { jQuery.dequeue( elem, type ); }, hooks ); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue " + type + ".run", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); 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 ); 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, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { count++; tmp.add( resolve ); } } resolve(); return defer.promise( object ); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, 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, nodeHook, boolHook, fixSpecified; 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( 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 ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; 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 ) { classNames = ( value || "" ).split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { 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( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { 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 self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, 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 && name in jQuery.attrFn ) { 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, l, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.toLowerCase().split( rspace ); l = attrNames.length; for ( ; i < l; 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; } } } }); // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; // 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.nodeValue !== "" : ret.specified ) ? ret.nodeValue : 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.nodeValue = value + "" ); } }; // Apply the nodeHook to tabindex jQuery.attrHooks.tabindex.set = nodeHook.set; // 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)$/, rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, quickParse = function( selector ) { var quick = rquickIs.exec( selector ); if ( quick ) { // 0 1 2 3 // [ _, tag, id, class ] quick[1] = ( quick[1] || "" ).toLowerCase(); quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); } return quick; }, quickIs = function( elem, m ) { var attrs = elem.attributes || {}; return ( (!m[1] || elem.nodeName.toLowerCase() === m[1]) && (!m[2] || (attrs.id || {}).value === m[2]) && (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) ); }, 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, quick, 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, quick: selector && quickParse( 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 elemData = jQuery.hasData( elem ) && jQuery._data( elem ), t, tns, type, origType, namespaces, origCount, j, events, special, handle, eventType, handleObj; 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 ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { handle = elemData.handle; if ( handle ) { handle.elem = null; } // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, [ "events", "handle" ], 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 type = event.type || event, namespaces = [], cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; // 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; old = null; for ( ; 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 && old === elem.ownerDocument ) { 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( 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 handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments, 0 ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = [], i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; // 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") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this.ownerDocument || this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process events on disabled elements (#6911, #8165) if ( cur.disabled !== true ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = ( handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) ); } 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; add metaKey if it's not there (#3368, IE6/7/8) if ( event.metaKey === undefined ) { event.metaKey = event.ctrlKey; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, 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 ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, 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 target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector, ret; // 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 && !form._submit_attached ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); 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; 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 ) && !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 ); } }); 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 ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var 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 ( var 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 ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } 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 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache" + (Math.random() + '').replace('.', ''), done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set, seed ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { filter = Expr.filter[ type ]; left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); pass = not ^ found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Utility function for retreiving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // 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" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var first, last, doneName, parent, cache, count, diff, type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Sizzle.attr ? Sizzle.attr( elem, name ) : Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : !type && Sizzle.attr ? result != null : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } // Expose origPOS // "global" as in regardless of relation to brackets/parens Expr.match.globalPOS = origPOS; var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // 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 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, 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, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context, seed ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; Sizzle.selectors.attrMap = {}; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.globalPOS, // 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 self = this, i, l; 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; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; 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 targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". POS.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 ret = [], i, l, cur = this[0]; // Array (deprecated as of jQuery 1.7) if ( jQuery.isArray( selectors ) ) { var level = 1; while ( cur && cur.ownerDocument && cur !== context ) { for ( i = 0; i < selectors.length; i++ ) { if ( jQuery( cur ).is( selectors[ i ] ) ) { ret.push({ selector: selectors[ i ], elem: cur, level: level }); } } cur = cur.parentNode; level++; } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // 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 ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, 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; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // 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+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, 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 ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( 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.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery.clean( arguments ); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery.clean(arguments) ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { 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, "" ) : null; } if ( typeof value === "string" && !rnoInnerhtml.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 ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.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 ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || ( l > 1 && i < lastIndex ) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { jQuery.ajax({ type: "GET", global: false, url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var 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(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // 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 ); // Clear flags for bubbling special change/submit events, they must // be reattached when the newly cloned events are first activated dest.removeAttribute( "_submit_attached" ); dest.removeAttribute( "_change_attached" ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc, first = args[ 0 ]; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // 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 && doc === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { cacheable = true; cacheresults = jQuery.fragments[ first ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ first ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( 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 ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "input" ) { fixDefaultChecked( elem ); // Skip scripts, get other children } else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } // Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js function shimCloneNode( elem ) { var div = document.createElement( "div" ); safeFragment.appendChild( div ); div.innerHTML = elem.outerHTML; return div.firstChild; } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, // IE<=8 does not properly clone detached, unknown element nodes clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ? elem.cloneNode( true ) : shimCloneNode( elem ); 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 checkScriptType, script, j, ret = []; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"), safeChildNodes = safeFragment.childNodes, remove; // Append wrapper element to unknown element safe doc fragment if ( context === document ) { // Use the fragment we've already created for this document safeFragment.appendChild( div ); } else { // Use a fragment created with the owner document createSafeFragment( context ).appendChild( div ); } // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( 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; // Clear elements from DocumentFragment (safeFragment or otherwise) // to avoid hoarding elements. Fixes #11356 if ( div ) { div.parentNode.removeChild( div ); // Guard against -1 index exceptions in FF3.6 if ( safeChildNodes.length > 0 ) { remove = safeChildNodes[ safeChildNodes.length - 1 ]; if ( remove && remove.parentNode ) { remove.parentNode.removeChild( remove ); } } } } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { script = ret[i]; if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) { scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script ); } else { if ( script.nodeType === 1 ) { var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( script ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnum = /^[\-+]?(?:\d*\.)?\d+$/i, rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i, rrelNum = /^([\-+])=([\-+.\de]+)/, rmargin = /^margin/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, // order is important! cssExpand = [ "Top", "Right", "Bottom", "Left" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.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 ); }; 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; } else { return elem.style.opacity; } } } }, // 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, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { 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 )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}, ret, name; // 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; } }); // DEPRECATED in 1.3, Use jQuery.css() instead jQuery.curCSS = jQuery.css; if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle, width, style = elem.style; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } // A tribute to the "awesome hack by Dean Edwards" // WebKit uses "computed value (percentage if specified)" instead of "used value" for margins // which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) { width = style.width; style.width = ret; ret = computedStyle.width; style.width = width; } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, uncomputed, 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 && (uncomputed = style[ name ]) ) { ret = uncomputed; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( rnumnonpx.test( ret ) ) { // 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; }; } curCSS = getComputedStyle || currentStyle; function getWidthOrHeight( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, i = name === "width" ? 1 : 0, len = 4; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i += 2 ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // 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; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i += 2 ) { val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0; } } } return val + "px"; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWidthOrHeight( elem, name, extra ); } else { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } } }, set: function( elem, value ) { return rnum.test( value ) ? value + "px" : value; } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, 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, "" ) ) === "" ) { // 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; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready 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, "margin-right" ); } else { return elem.style.marginRight; } }); } }; } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( 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; } }; }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #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, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, 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 = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts, // 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 = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // 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.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.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, 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 // 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 || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { 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 || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( 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.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == 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 false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #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 jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // 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 ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for ( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for ( key in s.converters ) { if ( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if ( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for ( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( 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 // #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, xhrCallbacks; // 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 xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // 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 occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { 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 elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback ); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( (display === "" && jQuery.css(elem, "display") === "none") || !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data( elem, "olddisplay" ) || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { var elem, display, i = 0, j = this.length; for ( ; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = jQuery.css( elem, "display" ); if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed( speed, easing, callback ); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); function doAnimation() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, e, hooks, replace, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; // first pass over propertys to expand / normalize for ( p in prop ) { name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) { replace = hooks.expand( prop[ name ] ); delete prop[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'p' from above because we have the correct "name" for ( p in replace ) { if ( ! ( p in prop ) ) { prop[ p ] = replace[ p ]; } } } } for ( name in prop ) { val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) { this.style.display = "inline-block"; } else { this.style.zoom = 1; } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test( val ) ) { // Tracks whether to show or hide based on private // data attached to the element method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 ); if ( method ) { jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" ); e[ method ](); } else { e[ val ](); } } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ( (end || 1) / e.cur() ) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; } return optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var index, hadTimers = false, timers = jQuery.timers, data = jQuery._data( this ); // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } function stopQueue( elem, data, index ) { var hooks = data[ index ]; jQuery.removeData( elem, index, true ); hooks.stop( gotoEnd ); } if ( type == null ) { for ( index in data ) { if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) { stopQueue( this, data, index ); } } } else if ( data[ index = type + ".run" ] && data[ index ].stop ){ stopQueue( this, data, index ); } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { if ( gotoEnd ) { // force the next step to be the last timers[ index ]( true ); } else { timers[ index ].saveState(); } hadTimers = true; 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 ( !( gotoEnd && hadTimers ) ) { jQuery.dequeue( this, type ); } }); } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx( "show", 1 ), slideUp: genFx( "hide", 1 ), slideToggle: genFx( "toggle", 1 ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // 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( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p ) { return p; }, swing: function( p ) { return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } ( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this ); }, // Get the current size cur: function() { if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = fxNow || createFxNow(); this.end = to; this.now = this.start = from; this.pos = this.state = 0; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); function t( gotoEnd ) { return self.step( gotoEnd ); } t.queue = this.options.queue; t.elem = this.elem; t.saveState = function() { if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { if ( self.options.hide ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } else if ( self.options.show ) { jQuery._data( self.elem, "fxshow" + self.prop, self.end ); } } }; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { var dataShow = jQuery._data( this.elem, "fxshow" + this.prop ); // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any flash of content if ( dataShow !== undefined ) { // This show is picking up where a previous hide or show left off this.custom( this.cur(), dataShow ); } else { this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() ); } // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom( this.cur(), 0 ); }, // Each step of an animation step: function( gotoEnd ) { var p, n, complete, t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( p in options.animatedProperties ) { if ( options.animatedProperties[ p ] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function( index, value ) { elem.style[ "overflow" + value ] = options.overflow[ index ]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery( elem ).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[ p ] ); jQuery.removeData( elem, "fxshow" + p, true ); // Toggle data is no longer needed jQuery.removeData( elem, "toggle" + p, true ); } } // Execute the complete function // in the event that the complete function throws an exception // we must ensure it won't be called twice. #5684 complete = options.complete; if ( complete ) { options.complete = false; complete.call( elem ); } } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ( (this.end - this.start) * this.pos ); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timer, timers = jQuery.timers, i = 0; for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = fx.now + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); // Ensure props that can't be negative don't go there on undershoot easing jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) { // exclude marginTop, marginLeft, marginBottom and marginRight from this list if ( prop.indexOf( "margin" ) ) { jQuery.fx.step[ prop ] = function( fx ) { jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit ); }; } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( 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 === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // 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( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var getOffset, rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { getOffset = function( elem, doc, docElem, box ) { try { box = elem.getBoundingClientRect(); } catch(e) {} // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow( doc ), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { getOffset = function( elem, doc, docElem ) { var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var elem = this[0], doc = elem && elem.ownerDocument; if ( !doc ) { return null; } if ( elem === doc.body ) { return jQuery.offset.bodyOffset( elem ); } return getOffset( elem, doc, doc.documentElement ); }; 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 null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {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 ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ 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 width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { var clientProp = "client" + name, scrollProp = "scroll" + name, offsetProp = "offset" + name; // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : this[ type ]() : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : this[ type ]() : null; }; jQuery.fn[ type ] = function( value ) { return jQuery.access( this, function( elem, type, value ) { var doc, docElemProp, orig, ret; if ( jQuery.isWindow( elem ) ) { // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat doc = elem.document; docElemProp = doc.documentElement[ clientProp ]; return jQuery.support.boxModel && docElemProp || doc.body && doc.body[ clientProp ] || docElemProp; } // Get document width or height if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater doc = elem.documentElement; // when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height] // so we can't use max, as it'll choose the incorrect offset[Width/Height] // instead we use the correct client[Width/Height] // support:IE6 if ( doc[ clientProp ] >= doc[ scrollProp ] ) { return doc[ clientProp ]; } return Math.max( elem.body[ scrollProp ], doc[ scrollProp ], elem.body[ offsetProp ], doc[ offsetProp ] ); } // Get width or height on the element if ( value === undefined ) { orig = jQuery.css( elem, type ); ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; } // Set the width or height on the element jQuery( elem ).css( type, value ); }, type, value, arguments.length, 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 );
webpack.local.config.js
gravitron07/brentayersV6
var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); /** * This is the Webpack configuration file for local development. It contains * local-specific configuration such as the React Hot Loader, as well as: * * - The entry point of the application * - Where the output file should be * - Which loaders to use on what files to properly transpile the source * * For more information, see: http://webpack.github.io/docs/configuration.html */ module.exports = { // Efficiently evaluate modules with source maps devtool: "eval", // Set entry point to ./src/main and include necessary files for hot load entry: [ "webpack-dev-server/client?http://localhost:9090", "webpack/hot/only-dev-server", "./src/main" ], // This will not actually create a bundle.js file in ./build. It is used // by the dev server for dynamic hot loading. output: { path: __dirname + "/build/", filename: "app.js", publicPath: "http://localhost:9090/build/" }, // Necessary plugins for hot load plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new ExtractTextPlugin('style.css', { allChunks: true }) ], // Transform source code using Babel and React Hot Loader module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ["react-hot", "babel-loader"] }, { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader') }, { test: /\.(jpe?g|jpg|png|gif|svg)$/i, loaders: [ 'file?hash=sha512&digest=hex&name=[hash].[ext]', 'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false' ] }, { test: /\.(jpg|png)$/, loader: 'file-loader', options: { name: '[path][name].[hash].[ext]', }, } ] }, // Automatically transform files with these extensions resolve: { extensions: ['', '.js', '.jsx', '.css'] }, // Additional plugins for CSS post processing using postcss-loader postcss: [ require('autoprefixer'), // Automatically include vendor prefixes require('postcss-nested') // Enable nested rules, like in Sass ] }
ui/src/main/js/components/JobOverview.js
rdelval/aurora
import React from 'react'; import JobHistory from 'components/JobHistory'; import JobStatus from 'components/JobStatus'; import PanelGroup from 'components/Layout'; import Loading from 'components/Loading'; import Tabs from 'components/Tabs'; import { isNully } from 'utils/Common'; export default function JobOverview(props) { if (isNully(props.tasks)) { return <PanelGroup><Loading /></PanelGroup>; } return (<Tabs activeTab={props.queryParams.jobView} className='job-overview' onChange={props.onViewChange}> {JobStatus(props)} {JobHistory(props)} </Tabs>); }
packages/material-ui/src/Grow/Grow.js
allanalexandre/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import { Transition } from 'react-transition-group'; import withTheme from '../styles/withTheme'; import { reflow, getTransitionProps } from '../transitions/utils'; import { useForkRef } from '../utils/reactHelpers'; function getScale(value) { return `scale(${value}, ${value ** 2})`; } const styles = { entering: { opacity: 1, transform: getScale(1), }, entered: { opacity: 1, // Use translateZ to scrolling issue on Chrome. transform: `${getScale(1)} translateZ(0)`, }, }; /** * The Grow transition is used by the [Tooltip](/components/tooltips/) and * [Popover](/components/popover/) components. * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally. */ const Grow = React.forwardRef(function Grow(props, ref) { const { children, in: inProp, onEnter, onExit, style, theme, timeout = 'auto', ...other } = props; const timer = React.useRef(); const autoTimeout = React.useRef(); const handleRef = useForkRef(children.ref, ref); const handleEnter = node => { reflow(node); // So the animation always start from the start. const { duration: transitionDuration, delay } = getTransitionProps( { style, timeout }, { mode: 'enter', }, ); let duration = 0; if (timeout === 'auto') { duration = theme.transitions.getAutoHeightDuration(node.clientHeight); autoTimeout.current = duration; } else { duration = transitionDuration; } node.style.transition = [ theme.transitions.create('opacity', { duration, delay, }), theme.transitions.create('transform', { duration: duration * 0.666, delay, }), ].join(','); if (onEnter) { onEnter(node); } }; const handleExit = node => { let duration = 0; const { duration: transitionDuration, delay } = getTransitionProps( { style, timeout }, { mode: 'exit', }, ); if (timeout === 'auto') { duration = theme.transitions.getAutoHeightDuration(node.clientHeight); autoTimeout.current = duration; } else { duration = transitionDuration; } node.style.transition = [ theme.transitions.create('opacity', { duration, delay, }), theme.transitions.create('transform', { duration: duration * 0.666, delay: delay || duration * 0.333, }), ].join(','); node.style.opacity = '0'; node.style.transform = getScale(0.75); if (onExit) { onExit(node); } }; const addEndListener = (_, next) => { if (timeout === 'auto') { timer.current = setTimeout(next, autoTimeout.current || 0); } }; React.useEffect(() => { return () => { clearTimeout(timer.current); }; }, []); return ( <Transition appear in={inProp} onEnter={handleEnter} onExit={handleExit} addEndListener={addEndListener} timeout={timeout === 'auto' ? null : timeout} {...other} > {(state, childProps) => { return React.cloneElement(children, { style: { opacity: 0, transform: getScale(0.75), visibility: state === 'exited' && !inProp ? 'hidden' : undefined, ...styles[state], ...style, ...children.props.style, }, ref: handleRef, ...childProps, }); }} </Transition> ); }); Grow.propTypes = { /** * A single child content element. */ children: PropTypes.element, /** * If `true`, show the component; triggers the enter or exit animation. */ in: PropTypes.bool, /** * @ignore */ onEnter: PropTypes.func, /** * @ignore */ onExit: PropTypes.func, /** * @ignore */ style: PropTypes.object, /** * @ignore */ theme: PropTypes.object.isRequired, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. * * Set to 'auto' to automatically calculate transition time based on height. */ timeout: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }), PropTypes.oneOf(['auto']), ]), }; Grow.muiSupportAuto = true; export default withTheme(Grow);
findyour3d/static/js/jquery.1.11.1.js
hqpr/findyour3d
/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | 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=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.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,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(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 ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.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===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||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 fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.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},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.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=fb.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=fb.selectors={cacheLength:50,createPseudo:hb,match:X,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(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===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]||fb.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]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.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(cb,db).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("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).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 Z.test(a.nodeName)},input:function(a){return Y.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:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(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]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.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=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[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?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var 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=[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(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(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 vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(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?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(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 vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.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(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.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(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(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(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
src/js/components/icons/base/CommandLine.js
codeswan/grommet
import React from 'react'; import Cli from './Cli'; export default (props) => { console.warn( 'CommandLine has been renamed to Cli.' + ' Plese update your import statement.' ); return <Cli {...props} />; };
src/containers/AsyncApp/index.js
Junicus/fcc-localweather
import React from 'react'; import { connect } from 'react-redux'; import { getLocation } from '../../actions'; import CurrentWeatherContainer from '../CurrentWeatherContainer'; import HourlyWeatherContainer from '../HourlyWeatherContainer'; import DailyForecastContainer from '../DailyForecastContainer'; import './app.css' class AsyncApp extends React.Component { constructor(props) { super(props); } componentDidMount() { const { dispatch } = this.props; dispatch(getLocation()); } render() { return ( <div className="app-outer app-background-default"> <div className="app-inner"> <div className="app-weather-today"> <CurrentWeatherContainer /> <HourlyWeatherContainer /> </div> <DailyForecastContainer /> </div> </div> ) } } function mapStateToProps(state) { const { weather } = state; return { weather }; } export default connect(mapStateToProps)(AsyncApp);
src/index.js
ferryhinardi/swapii_ass
/* eslint-disable import/default */ import React from 'react'; import {render} from 'react-dom'; import { Provider } from 'react-redux'; import { Router, browserHistory } from 'react-router'; import routes from './routes'; import configureStore from './store/configureStore'; require('./favicon.ico'); // Tell webpack to load favicon.ico import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page. import './styles/material/material.min.css'; import './styles/material/material.min.js'; // import { syncHistoryWithStore } from 'react-router-redux'; const store = configureStore(); // Create an enhanced history that syncs navigation events with the store // const history = syncHistoryWithStore(browserHistory, store); const history = browserHistory; render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('app') );
src/components/Sidebar/Sidebar.js
siddhant3s/crunchgraph
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import Arbiter from 'promissory-arbiter'; import s from './Sidebar.css'; const infoBoxStyle = { overflow: 'auto', color: 'blue', borderTop: '3px solid #b3d4fc', paddingLeft: '12px', marginTop: '10px', fontSize: '12px', height: '400px', }; class Sidebar extends React.Component { state = { nodes: ['530896', '623209'] } onType = (e, i) => { const nodes = [...this.state.nodes]; nodes[i] = e.target.value; this.setState({ nodes }); } addMore = () => { const nodes = [...this.state.nodes]; nodes.push(''); this.setState({ nodes }); } find = () => { const nodes = [...this.state.nodes]; const url = `http://localhost:3001/data/shortestPaths?${nodes.map(n => `ids[]=${n}`).join('&')}`; fetch(url) .then(r => r.json()) .then(d => Arbiter.publish('data_fetched', d)); } render() { const that = this; return ( <div className={s.root}> {this.state.nodes.map((n, i) => ( <div key={i}> Enter node:< br /> <input type="text" name="id[]" value={n} onChange={(e) => that.onType(e, i)} /><br /> </div> ))} <button onClick={this.find} value="Find">Find< /button> <div><button onClick={this.addMore}>+</button></div> <div className="node-selected-info" id="node-selected" style={infoBoxStyle}>Information of node selected</div> </div> ); } } export default withStyles(s)(Sidebar);
spec/javascripts/jsx/assignments/GradeSummary/components/FocusableViewSpec.js
djbender/canvas-lms
/* * Copyright (C) 2018 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {mount} from 'enzyme' import FocusableView from 'jsx/assignments/GradeSummary/components/FocusableView' // This rule does not apply for these specs. /* eslint-disable react/prop-types */ QUnit.module('GradeSummary FocusableView', suiteHooks => { let $container let renderChildren let wrapper suiteHooks.beforeEach(() => { $container = document.createElement('div') document.body.appendChild($container) }) suiteHooks.afterEach(() => { wrapper.unmount() $container.remove() }) function mountComponent() { wrapper = mount(<FocusableView>{renderChildren}</FocusableView>, {attachTo: $container}) } const keyCodeMap = { down: 40, left: 37, right: 39, up: 38 } function scroll(direction) { const event = { keyCode: keyCodeMap[direction], preventDefault: sinon.spy() } wrapper.find(FocusableView).simulate('keyDown', event) return event } function horizontalScrollTarget() { return wrapper.find('.HorizontalTarget').getDOMNode() } function verticalScrollTarget() { return wrapper.find('.VerticalTarget').getDOMNode() } test('is focusable', () => { renderChildren = () => <span>Example</span> mountComponent() const node = wrapper.find(FocusableView).getDOMNode() node.focus() strictEqual(node, document.activeElement) }) test('is focusable via tabbing', () => { renderChildren = () => <span>Example</span> mountComponent() const node = wrapper.find(FocusableView).getDOMNode() strictEqual(node.getAttribute('tabindex'), '0') }) QUnit.module('when given a horizontal scroll reference', hooks => { const scrollTargetStyle = {height: '100px', overflow: 'auto', width: '100px'} const scrollContentStyle = {height: '500px', width: '500px'} let maxScrollLeft hooks.beforeEach(() => { renderChildren = props => ( <div className="HorizontalTarget" ref={props.horizontalScrollRef} style={scrollTargetStyle}> <div style={scrollContentStyle} /> </div> ) mountComponent() if (maxScrollLeft == null) { maxScrollLeft = 500 - horizontalScrollTarget().clientWidth } }) test('scrolls right on the scroll target', () => { scroll('right') strictEqual(horizontalScrollTarget().scrollLeft, 50) }) test('prevents default event behavior when scrolling right', () => { const event = scroll('right') strictEqual(event.preventDefault.callCount, 1) }) test('stops scrolling right at the rightmost limit', () => { horizontalScrollTarget().scrollLeft = maxScrollLeft - 10 scroll('right') strictEqual(horizontalScrollTarget().scrollLeft, maxScrollLeft) }) test('prevents default event behavior when scrolling to the rightmost limit', () => { horizontalScrollTarget().scrollLeft = maxScrollLeft - 10 const event = scroll('right') strictEqual(event.preventDefault.callCount, 1) }) test('does not scroll beyond the rightmost limit', () => { horizontalScrollTarget().scrollLeft = maxScrollLeft scroll('right') strictEqual(horizontalScrollTarget().scrollLeft, maxScrollLeft) }) test('does not prevent default event behavior when stopped at the rightmost limit', () => { horizontalScrollTarget().scrollLeft = maxScrollLeft const event = scroll('right') strictEqual(event.preventDefault.callCount, 0) }) test('scrolls left on the scroll target', () => { horizontalScrollTarget().scrollLeft = 250 scroll('left') strictEqual(horizontalScrollTarget().scrollLeft, 200) }) test('prevents default event behavior when scrolling left', () => { horizontalScrollTarget().scrollLeft = 250 const event = scroll('left') strictEqual(event.preventDefault.callCount, 1) }) test('stops scrolling left at the leftmost limit', () => { horizontalScrollTarget().scrollLeft = 10 scroll('left') strictEqual(horizontalScrollTarget().scrollLeft, 0) }) test('prevents default event behavior when scrolling to the leftmost limit', () => { horizontalScrollTarget().scrollLeft = 10 const event = scroll('left') strictEqual(event.preventDefault.callCount, 1) }) test('does not scroll beyond the leftmost limit', () => { horizontalScrollTarget().scrollLeft = 0 scroll('left') strictEqual(horizontalScrollTarget().scrollLeft, 0) }) test('does not prevent default event behavior when stopped at the leftmost limit', () => { horizontalScrollTarget().scrollLeft = 0 const event = scroll('left') strictEqual(event.preventDefault.callCount, 0) }) test('does not scroll down', () => { scroll('down') strictEqual(horizontalScrollTarget().scrollTop, 0) }) test('does not prevent default event behavior for down arrow', () => { horizontalScrollTarget().scrollLeft = 0 const event = scroll('down') strictEqual(event.preventDefault.callCount, 0) }) test('does not scroll up', () => { horizontalScrollTarget().scrollTop = 100 scroll('up') strictEqual(horizontalScrollTarget().scrollTop, 100) }) test('does not prevent default event behavior for up arrow', () => { horizontalScrollTarget().scrollTop = 100 const event = scroll('up') strictEqual(event.preventDefault.callCount, 0) }) }) QUnit.module('when given a vertical scroll reference', hooks => { const scrollTargetStyle = {height: '100px', overflow: 'auto', width: '100px'} const scrollContentStyle = {height: '500px', width: '500px'} let maxScrollTop hooks.beforeEach(() => { renderChildren = props => ( <div className="VerticalTarget" ref={props.verticalScrollRef} style={scrollTargetStyle}> <div style={scrollContentStyle} /> </div> ) mountComponent() if (maxScrollTop == null) { maxScrollTop = 500 - verticalScrollTarget().clientHeight } }) test('scrolls down on the scroll target', () => { scroll('down') strictEqual(verticalScrollTarget().scrollTop, 50) }) test('prevents default event behavior when scrolling down', () => { const event = scroll('down') strictEqual(event.preventDefault.callCount, 1) }) test('stops scrolling down at the bottommost limit', () => { verticalScrollTarget().scrollTop = maxScrollTop - 10 scroll('down') strictEqual(verticalScrollTarget().scrollTop, maxScrollTop) }) test('prevents default event behavior when scrolling to the bottommost limit', () => { verticalScrollTarget().scrollTop = maxScrollTop - 10 const event = scroll('down') strictEqual(event.preventDefault.callCount, 1) }) test('does not scroll beyond the bottommost limit', () => { verticalScrollTarget().scrollTop = maxScrollTop scroll('down') strictEqual(verticalScrollTarget().scrollTop, maxScrollTop) }) test('does not prevent default event behavior when stopped at the bottommost limit', () => { verticalScrollTarget().scrollTop = maxScrollTop const event = scroll('down') strictEqual(event.preventDefault.callCount, 0) }) test('scrolls up on the scroll target', () => { verticalScrollTarget().scrollTop = 250 scroll('up') strictEqual(verticalScrollTarget().scrollTop, 200) }) test('prevents default event behavior when scrolling up', () => { verticalScrollTarget().scrollTop = 250 const event = scroll('up') strictEqual(event.preventDefault.callCount, 1) }) test('stops scrolling up at the topmost limit', () => { verticalScrollTarget().scrollTop = 10 scroll('up') strictEqual(verticalScrollTarget().scrollTop, 0) }) test('prevents default event behavior when scrolling to the topmost limit', () => { verticalScrollTarget().scrollTop = 10 const event = scroll('up') strictEqual(event.preventDefault.callCount, 1) }) test('does not scroll beyond the topmost limit', () => { verticalScrollTarget().scrollTop = 0 scroll('up') strictEqual(verticalScrollTarget().scrollTop, 0) }) test('does not prevent default event behavior when stopped at the topmost limit', () => { verticalScrollTarget().scrollTop = 0 const event = scroll('up') strictEqual(event.preventDefault.callCount, 0) }) test('does not scroll right', () => { scroll('right') strictEqual(verticalScrollTarget().scrollLeft, 0) }) test('does not prevent default event behavior for right arrow', () => { const event = scroll('right') strictEqual(event.preventDefault.callCount, 0) }) test('does not scroll left', () => { verticalScrollTarget().scrollLeft = 100 scroll('left') strictEqual(verticalScrollTarget().scrollLeft, 100) }) test('does not prevent default event behavior for left arrow', () => { verticalScrollTarget().scrollLeft = 100 const event = scroll('left') strictEqual(event.preventDefault.callCount, 0) }) }) QUnit.module('when given the same horizontal and vertical scroll reference', hooks => { const scrollTargetStyle = {height: '200px', overflow: 'auto', width: '200px'} const scrollContentStyle = {height: '500px', width: '500px'} hooks.beforeEach(() => { renderChildren = props => { const bindRefs = ref => { props.horizontalScrollRef(ref) props.verticalScrollRef(ref) } return ( <div className="HorizontalTarget VerticalTarget" ref={bindRefs} style={scrollTargetStyle}> <div style={scrollContentStyle} /> </div> ) } mountComponent() }) test('scrolls right on the scroll target', () => { scroll('right') strictEqual(horizontalScrollTarget().scrollLeft, 50) }) test('scrolls left on the scroll target', () => { horizontalScrollTarget().scrollLeft = 250 scroll('left') strictEqual(horizontalScrollTarget().scrollLeft, 200) }) test('scrolls down on the scroll target', () => { scroll('down') strictEqual(verticalScrollTarget().scrollTop, 50) }) test('scrolls up on the scroll target', () => { verticalScrollTarget().scrollTop = 250 scroll('up') strictEqual(verticalScrollTarget().scrollTop, 200) }) }) QUnit.module('when given different horizontal and vertical scroll references', hooks => { const scrollTargetStyle = {height: '200px', overflow: 'auto', width: '200px'} const scrollContentStyle = {height: '500px', width: '500px'} hooks.beforeEach(() => { renderChildren = props => ( <div> <div className="VerticalTarget" ref={props.verticalScrollRef} style={scrollTargetStyle}> <div style={scrollContentStyle} /> </div> <div className="HorizontalTarget" ref={props.horizontalScrollRef} style={scrollTargetStyle} > <div style={scrollContentStyle} /> </div> </div> ) mountComponent() }) test('scrolls right on the horizontal scroll target', () => { scroll('right') strictEqual(horizontalScrollTarget().scrollLeft, 50) }) test('does not scroll the vertical target right', () => { scroll('right') strictEqual(verticalScrollTarget().scrollLeft, 0) }) test('scrolls left on the horizontal scroll target', () => { horizontalScrollTarget().scrollLeft = 250 scroll('left') strictEqual(horizontalScrollTarget().scrollLeft, 200) }) test('does not scroll the vertical target left', () => { verticalScrollTarget().scrollLeft = 100 scroll('left') strictEqual(verticalScrollTarget().scrollLeft, 100) }) test('scrolls down on the vertical scroll target', () => { scroll('down') strictEqual(verticalScrollTarget().scrollTop, 50) }) test('does not scroll the horizontal target down', () => { scroll('down') strictEqual(horizontalScrollTarget().scrollTop, 0) }) test('scrolls up on the vertical scroll target', () => { verticalScrollTarget().scrollTop = 250 scroll('up') strictEqual(verticalScrollTarget().scrollTop, 200) }) test('does not scroll the horizontal target up', () => { horizontalScrollTarget().scrollTop = 250 scroll('up') strictEqual(horizontalScrollTarget().scrollTop, 250) }) }) })
client/src/components/Game/Card.js
patteri/slave-cardgame
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import deck from '../../utils/deck'; import './style.css'; const Card = ({ card, selected, onClick }) => ( <input type="image" className={classNames('Game-card', { selected: selected })} src={deck.getCard(card).src} onClick={onClick} alt={`${card.suit}-${card.value}`} /> ); Card.propTypes = { card: PropTypes.object.isRequired, selected: PropTypes.bool, onClick: PropTypes.func }; export default Card;
ui/src/components/member/Member.js
yahoo/athenz
/* * Copyright 2020 Verizon Media * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import Tag from '../denali/Tag'; import styled from '@emotion/styled'; import DateUtils from '../utils/DateUtils'; import Menu from '../denali/Menu/Menu'; import Icon from '../denali/icons/Icon'; import { colors } from '../denali/styles'; const StyledTag = styled(Tag)` background: rgba(53, 112, 244, 0.08); color: #d5d5d5; &:hover { background: #ffffff; } font-size: 14px; height: 28px; line-height: 14px; margin: 5px 15px 5px 0; padding: 7px 8px 7px 10px; `; const StyledTagFullNameExpiry = styled.span` font-size: 11px; `; const MenuDiv = styled.div` padding: 5px 10px; background-color: black; color: white; font-size: 12px; `; const StyledAnchor = styled.a` text-decoration: none; `; const StyledAnchorActiveInline = { color: colors.linkActive }; const StyledTagFullNameExpiryActiveInline = { color: colors.black }; export default class Member extends React.Component { constructor(props) { super(props); this.onClickRemove = this.onClickRemove.bind(this); this.onClickPendingRemove = this.onClickPendingRemove.bind(this); this.localDate = new DateUtils(); this.state = {}; } onClickRemove() { this.props.onClickRemove(this.props.item.memberName); } onClickPendingRemove() { this.props.onClickPendingRemove(this.props.item.memberName); } render() { let exp = this.props.item.expiration; if (exp) { exp = this.localDate.getLocalDate(exp, 'UTC', 'UTC'); } let review = this.props.item.reviewReminder; if (review) { review = this.localDate.getLocalDate(review, 'UTC', 'UTC'); } let fullName = ''; let shortId = this.props.item.memberName.startsWith('user.') ? this.props.item.memberName.substr( 5, this.props.item.memberName.length ) : this.props.item.memberName; if (this.props.item.memberFullName) { fullName = ( <StyledTagFullNameExpiry style={ this.props.item.systemDisabled ? {} : StyledTagFullNameExpiryActiveInline } > ({this.props.item.memberFullName}) </StyledTagFullNameExpiry> ); } //TODO link anchor to user profile link if (!this.props.item.approved) { return ( <StyledTag onClick={this.props.onClick} onClickRemove={this.onClickPendingRemove} noanim={this.props.noanim} disabled={this.props.item.systemDisabled} > <StyledAnchor style={ this.props.item.systemDisabled ? {} : StyledAnchorActiveInline } > {' '} {review && ( <StyledTagFullNameExpiry style={ this.props.item.systemDisabled ? {} : StyledTagFullNameExpiryActiveInline } > <Menu placement='bottom-start' trigger={ <span> <Icon enableTitle={false} icon={'assignment-priority'} color={colors.icons} isLink size={'1.25em'} verticalAlign={'text-bottom'} /> </span> } > <MenuDiv>{'Reminder: ' + review}</MenuDiv> </Menu> </StyledTagFullNameExpiry> )} {this.props.item.memberName}{' '} </StyledAnchor> {fullName} {exp && ( <StyledTagFullNameExpiry style={ this.props.item.systemDisabled ? {} : StyledTagFullNameExpiryActiveInline } > {' | '} {exp} </StyledTagFullNameExpiry> )} </StyledTag> ); } else { //TODO link anchor to user profile link return ( <Tag data-testid={'role-member'} onClick={this.props.onClick} onClickRemove={this.onClickRemove} noanim={this.props.noanim} disabled={this.props.item.systemDisabled} > <StyledAnchor style={ this.props.item.systemDisabled ? {} : StyledAnchorActiveInline } > {' '} {review && ( <StyledTagFullNameExpiry style={ this.props.item.systemDisabled ? {} : StyledTagFullNameExpiryActiveInline } > <Menu placement='bottom-start' trigger={ <span> <Icon enableTitle={false} icon={'assignment-priority'} color={colors.icons} isLink size={'1.25em'} verticalAlign={'text-bottom'} /> </span> } > <MenuDiv>{'Reminder: ' + review}</MenuDiv> </Menu> </StyledTagFullNameExpiry> )} {this.props.item.memberName}{' '} </StyledAnchor> {fullName} {exp && ( <StyledTagFullNameExpiry style={ this.props.item.systemDisabled ? {} : StyledTagFullNameExpiryActiveInline } > {' | '} {exp} </StyledTagFullNameExpiry> )} </Tag> ); } } }
tests/components/TextBoxQuestionTest.js
flexiform/flexiform-fill-ui
/** * Copyright 2016 ReSys OÜ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*eslint-env node, mocha */ /*global expect */ /*eslint no-console: 0*/ import { shallow, mount } from 'enzyme'; import React from 'react'; import Immutable from 'immutable'; import {TextBoxQuestion} from '../../src/components/TextBoxQuestion'; import Adapter from 'enzyme-adapter-react-16'; import Enzyme from 'enzyme' Enzyme.configure({ adapter: new Adapter() }); describe('TextBoxQuestion', () => { it('should have its component name as default className', () => { let question = { id: 'testq', type: 'text' }; let wrapper = shallow(<TextBoxQuestion question={[question.id, Immutable.fromJS(question)]}/>); expect(wrapper.props().className).to.equal('dialob-item dialob-itemtype-text '); }); });
src/assets/js/react/components/Template/TemplateListItem.js
blueliquiddesigns/gravity-forms-pdf-extended
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { withRouter } from 'react-router-dom' import { updateTemplateParam } from '../../actions/templates' import TemplateScreenshot from './TemplateScreenshot' import ShowMessage from '../ShowMessage' import { TemplateDetails, Group } from './TemplateListItemComponents' import { Name } from './TemplateSingleComponents' import TemplateActivateButton from './TemplateActivateButton' /** * Display the individual template item for usage our template list * * @package Gravity PDF * @copyright Copyright (c) 2020, Blue Liquid Designs * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 4.1 */ /** * React Component * * @since 4.1 */ export class TemplateListItem extends React.Component { /** * @since 4.1 */ static propTypes = { history: PropTypes.object, template: PropTypes.object, activeTemplate: PropTypes.string, updateTemplateParam: PropTypes.func, activateText: PropTypes.string, templateDetailsText: PropTypes.string } /** * Check if the Enter key is pressed and not focused on a button * then display the template details page * * @param {Object} e Event * * @since 4.1 */ maybeShowDetailedTemplate = (e) => { /* Show detailed template when the Enter key is pressed and the active element doesn't include a 'button' class */ if (e.keyCode === 13 && (e.target.className.indexOf('button') === -1)) { this.showDetailedTemplate() } } /** * Update the URL to show the PDF template details page * * @since 4.1 */ showDetailedTemplate = () => { this.props.history.push('/template/' + this.props.template.id) } /** * Call Redux action to remove any stored messages for this template * * @since 4.1 */ removeMessage = () => { this.props.updateTemplateParam(this.props.template['id'], 'message', null) } /** * @since 4.1 */ render () { const item = this.props.template const isActiveTemplate = this.props.activeTemplate === item['id'] const isCompatible = item['compatible'] const activeTemplate = (isActiveTemplate) ? 'active theme' : 'theme' return ( <div onClick={this.showDetailedTemplate} onKeyDown={this.maybeShowDetailedTemplate} className={activeTemplate} data-slug={item['id']} tabIndex="150"> <TemplateScreenshot image={item['screenshot']} /> {item['error'] ? <ShowMessage text={item['error']} error={true} /> : null} {item['message'] ? <ShowMessage text={item['message']} dismissableCallback={this.removeMessage} dismissable={true} delay={12000} /> : null} <TemplateDetails label={this.props.templateDetailsText} /> <Group group={item['group']} /> <Name name={item['template']} /> <div className="theme-actions"> {!isActiveTemplate && isCompatible ? <TemplateActivateButton template={this.props.template} buttonText={this.props.activateText} /> : null} </div> </div> ) } } /** * Map state to props * * @param {Object} state The current Redux State * * @returns {{activeTemplate: string}} * * @since 4.1 */ const mapStateToProps = (state) => { return { activeTemplate: state.template.activeTemplate } } /** * Map actions to props * * @param {func} dispatch Redux dispatcher * * @returns {{updateTemplateParam: (function(id=string, name=string, value=string))}} * * @since 4.1 */ const mapDispatchToProps = (dispatch) => { return { updateTemplateParam: (id, name, value) => { dispatch(updateTemplateParam(id, name, value)) } } } /** * Maps our Redux store to our React component * * @since 4.1 */ export default withRouter(connect(mapStateToProps, mapDispatchToProps)(TemplateListItem))
packages/react/src/components/atoms/media/SiteLogo/index.js
massgov/mayflower
/** * SiteLogo module. * @module @massds/mayflower-react/SiteLogo * @requires module:@massds/mayflower-assets/scss/01-atoms/site-logo * @requires module:@massds/mayflower-assets/scss/01-atoms/image */ import React from 'react'; import PropTypes from 'prop-types'; import Image from 'MayflowerReactMedia/Image'; import getFallbackComponent from 'MayflowerReactComponents/utilities/getFallbackComponent'; const SiteLogo = ({ url, image, siteName, title, Wrapper }) => { const RenderedWrapper = getFallbackComponent(Wrapper, React.Fragment); return( <RenderedWrapper> <div className="ma__site-logo"> <a href={url.domain} title={title}> {image?.src && <Image {...image} />} {siteName && <span>{siteName}</span>} </a> </div> </RenderedWrapper> ); }; SiteLogo.propTypes = { /** The URL for the site */ url: PropTypes.shape({ /** The URL for the site root */ domain: PropTypes.string.isRequired }), /** The site logo image to display. */ image: PropTypes.shape(PropTypes.Image), /** An optional label to display next to the site logo. */ siteName: PropTypes.string, /** The title attribute for the site logo link. */ title: PropTypes.string, /** An uninstantiated component for rendering a wrapper around the site logo div. */ Wrapper: PropTypes.elementType }; SiteLogo.defaultProps = { image: { alt: '', width: 45, height: 45 } }; export default SiteLogo;
ajax/libs/forerunnerdb/1.3.484/fdb-core+views.min.js
Piicksarn/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/View");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/View":31,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":7,"../lib/Shim.IE8":30}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.mixin(e.prototype,"Mixin.Sorting"),d.synthesize(e.prototype,"primaryKey"),e.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},e.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},e.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":29}],4:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a,b,c){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c,d){this._store=[],this._keys=[],void 0!==b&&this.index(b),void 0!==c&&this.compareFunc(c),void 0!==d&&this.hashFunc(d),void 0!==a&&this.data(a)},d.addModule("BinaryTree",f),d.mixin(f.prototype,"Mixin.ChainReactor"),d.mixin(f.prototype,"Mixin.Sorting"),d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"compareFunc"),d.synthesize(f.prototype,"hashFunc"),d.synthesize(f.prototype,"indexDir"),d.synthesize(f.prototype,"keys"),d.synthesize(f.prototype,"index",function(a){return void 0!==a&&this.keys(this.extractKeys(a)),this.$super.call(this,a)}),f.prototype.extractKeys=function(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push({key:b,val:a[b]});return c},f.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},f.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},f.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},f.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.val?e=this.sortAsc(a[d.key],b[d.key]):-1===d.val&&(e=this.sortDesc(a[d.key],b[d.key])),0!==e)return e;return e},f.prototype._hashFunc=function(a){return a[this._keys[0].key]},f.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this._data?(b=this._compareFunc(this._data,a),0===b?(this.push(a),this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):-1===b?(this._right?this._right.insert(a):this._right=new f(a,this._index,this._compareFunc,this._hashFunc),!0):1===b?(this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):!1):(this.data(a),!0)},f.prototype.lookup=function(a,b){var c=this._compareFunc(this._data,a);return b=b||[],0===c&&(this._left&&this._left.lookup(a,b),b.push(this._data),this._right&&this._right.lookup(a,b)),-1===c&&this._right&&this._right.lookup(a,b),1===c&&this._left&&this._left.lookup(a,b),b},f.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},f.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},f.prototype.match=function(a,b){var c,d,f,g=new e,h=[],i=0;for(c=g.parseArr(this._index,{verbose:!0}),d=g.parseArr(a,{ignore:/\$/,verbose:!0}),f=0;f<c.length;f++)d[f]===c[f]&&(i++,h.push(d[f]));return{matchedKeys:h,totalKeyCount:d.length,score:i}},d.finishModule("BinaryTree"),b.exports=f},{"./Path":26,"./Shared":29}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),d.mixin(n.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"deferredCalls"),d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),d.synthesize(n.prototype,"metaData"),d.synthesize(n.prototype,"capped"),d.synthesize(n.prototype,"cappedSize"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",a,{oldData:b})}return this}return this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},n.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(n.prototype,"mongoEmulation"),n.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},n.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},n.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b),this.debug()&&console.log(this.logIdentifier()+" Updating some data");var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:e},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":var s=!0;b[p]>0?b.$max&&a[p]>=b.$max&&(s=!1):b[p]<0&&b.$min&&a[p]<=b.$min&&(s=!1),s&&(this._updateIncrement(a,p,b[p]),q=!0);break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+p+")";var t,u,v,w,x=a[p],y=x.length,z=!0,A=d&&d.$addToSet;for(b[p].$key?(v=!1,w=new h(b[p].$key),u=w.value(b[p])[0],delete b[p].$key):A&&A.key?(v=!1,w=new h(A.key),u=w.value(b[p])[0]):(u=this.jStringify(b[p]),v=!0),t=0;y>t;t++)if(v){if(this.jStringify(x[t])===u){z=!1;break}}else if(u===w.value(x[t])[0]){z=!1;break}z&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+p+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],d,"",{})){var B=b.$index;if(void 0===B)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[p],j,B),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;case"$toggle":this._updateProperty(a,p,!a[p]),q=!0;break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){if(g.length)switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c);this.isProcessingQueue()||this.emit("queuesComplete")},n.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},n.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainSend("insert",a,{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(n.prototype,"subsetOf"),n.prototype.isSubsetOf=function(a){return this._subsetOf===a},n.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},n.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I=this._metrics.create("find"),J=this.primaryKey(),K=this,L=!0,M={},N=[],O=[],P=[],Q={},R={},S=function(c){return K._match(c,a,b,"and",Q)};if(I.start(),a){if(I.time("analyseQuery"),c=this._analyseQuery(K.decouple(a),b,I),I.time("analyseQuery"),I.data("analysis",c),c.hasJoin&&c.queriesJoin){for(I.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],M[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];I.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(I.data("index.potential",c.indexMatch),I.data("index.used",c.indexMatch[0].index),I.time("indexLookup"),e=c.indexMatch[0].lookup||[],I.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(L=!1)):I.flag("usedIndex",!1),L&&(e&&e.length?(d=e.length,I.time("tableScan: "+d),e=e.filter(S)):(d=this._data.length,I.time("tableScan: "+d),e=this._data.filter(S)),I.time("tableScan: "+d)),b.$orderBy&&(I.time("sort"),e=this.sort(b.$orderBy,e),I.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(R.page=b.$page,R.pages=Math.ceil(e.length/b.$limit),R.records=e.length,b.$page&&b.$limit>0&&(I.data("cursor",R),e.splice(0,b.$page*b.$limit))),b.$skip&&(R.skip=b.$skip,e.splice(0,b.$skip),I.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(R.limit=b.$limit,e.length=b.$limit,I.data("limit",b.$limit)),b.$decouple&&(I.time("decouple"),e=this.decouple(e),I.time("decouple"),I.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(w=k,l=M[k]?M[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=K._resolveDynamicQuery(m[n].query,e[x])),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=K._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else N.push(e[x])}I.data("flag.join",!0)}if(N.length){for(I.time("removalQueue"),z=0;z<N.length;z++)y=e.indexOf(N[z]),y>-1&&e.splice(y,1);I.time("removalQueue")}if(b.$transform){for(I.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));I.time("transform"),I.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(I.time("transformOut"),e=this.transformOut(e),I.time("transformOut")),I.data("results",e.length)}else e=[];if(!b.$aggregate){I.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?O.push(z):0===b[z]&&P.push(z));if(I.time("scanFields"),O.length||P.length){for(I.data("flag.limitFields",!0),I.data("limitFields.on",O),I.data("limitFields.off",P),I.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(O.length&&A!==J&&-1===O.indexOf(A)&&delete G[A],P.length&&P.indexOf(A)>-1&&delete G[A])}I.time("limitFields")}if(b.$elemMatch){I.data("flag.elemMatch",!0),I.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(K._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}I.time("projection-elemMatch")}if(b.$elemsMatch){I.data("flag.elemsMatch",!0),I.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)K._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}I.time("projection-elemsMatch")}}return b.$aggregate&&(I.data("flag.aggregate",!0),I.time("aggregate"),H=new h(b.$aggregate),e=H.value(e),I.time("aggregate")),I.stop(),e.__fdbOp=I,e.$cursor=R,e},n.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g,i=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b):new h(a).value(b),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=new h(e.substr(3,e.length-3)).value(b)[0]:c[g]=e;break;case"object":c[g]=i._resolveDynamicQuery(e,b);break;default:c[g]=e}return c},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},n.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},n.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=String(c),e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f,g,h,i=a.shift(),j=[];if(a.length>0){for(b=this._sort(i,b),d=this.bucket(i.___fdbKey,b),e=d.order,g=d.buckets,h=0;h<e.length;h++)f=e[h],c=[].concat(a),j=j.concat(this._bucketSort(c,g[f]));return j}return this._sort(i,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),"$as"in b.$join[d][e]?r.push(b.$join[d][e].$as):r.push(e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={ parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},n.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},n.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof n?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+b+" because it does not exist and auto-create has been disabled!";return}this.debug()&&console.log(this.logIdentifier()+" Creating collection "+b)}if(this._collection[b]=this._collection[b]||new n(b,a).db(this),this._collection[b].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[b].capped(a.capped),this._collection[b].cappedSize(a.size)}return this._collection[b]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=n},{"./Crc":8,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":25,"./Path":26,"./ReactorIO":27,"./Shared":29}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":29}],7:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":9,"./Metrics.js":13,"./Overload":25,"./Shared":29}],8:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":13,"./Overload":25,"./Shared":29}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=new f,h=function(){};g.inOrder("hash");var i=function(){this.init.apply(this,arguments)};i.prototype.init=function(a,b,c){this._btree=new(h.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",i),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Sorting"),i.prototype.id=function(){return this._id},i.prototype.state=function(){return this._state},i.prototype.size=function(){return this._size},d.synthesize(i.prototype,"data"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"collection"),d.synthesize(i.prototype,"type"),d.synthesize(i.prototype,"unique"),i.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},i.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(h.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},i.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},i.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},i.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},i.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},i.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},i.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},i.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},i.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},i.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=i},{"./BinaryTree":4,"./Path":26,"./Shared":29}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":26,"./Shared":29}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":29}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":24,"./Shared":29}],14:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],15:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],16:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":25,"./Serialiser":28}],17:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],18:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){ d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":25}],19:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!this.db())throw"Cannot operate a "+a+" sub-query on an anonymous collection (one with no db set)!";if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],22:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":25}],23:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],24:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":26,"./Shared":29}],25:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",console.log("Overload: ",a),'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.valueOne=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.valueOne(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":29}],27:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":29}],28:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],29:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.484",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Tags":21,"./Mixin.Triggers":22,"./Mixin.Updating":23,"./Overload":25}],30:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],31:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate")},d.addModule("View",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.find=function(a,b){return this.publicData().find(a,b)},l.prototype.findOne=function(a,b){return this.publicData().findOne(a,b)},l.prototype.findById=function(a,b){return this.publicData().findById(a,b)},l.prototype.findSub=function(a,b,c,d){return this.publicData().findSub(a,b,c,d)},l.prototype.findSubOne=function(a,b,c,d){return this.publicData().findSubOne(a,b,c,d)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var b,d,e,f,g,h,i;if(c&&!c.isDropped()&&c._querySettings.query){if("insert"===a.type){if(b=a.data,b instanceof Array)for(f=[],i=0;i<b.length;i++)c._privateData._match(b[i],c._querySettings.query,c._querySettings.options,"and",{})&&(f.push(b[i]),g=!0);else c._privateData._match(b,c._querySettings.query,c._querySettings.options,"and",{})&&(f=b,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=c._privateData.diff(c._from.subset(c._querySettings.query,c._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=c._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=c._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var d=a.find(this._querySettings.query,this._querySettings.options);return this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data"),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._privateData.setData(j);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._privateData._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._privateData._updateSpliceMove(this._privateData._data,i,e);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){var d=this.publicData();return d.distinct.apply(d,arguments)},l.prototype.primaryKey=function(){return this.publicData().primaryKey()},l.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(l.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},l.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.prototype.transform=function(a){var b=this;return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformEnabled?(this._publicData||(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._transformIo=new j(this._privateData,this._publicData,function(a){var c=a.data;switch(a.type){case"primaryKey":b._publicData.primaryKey(c),this.chainSend("primaryKey",c);break;case"setData":b._publicData.setData(c),this.chainSend("setData",c);break;case"insert":b._publicData.insert(c),this.chainSend("insert",c);break;case"update":b._publicData.update(c.query,c.update,c.options),this.chainSend("update",c);break;case"remove":b._publicData.remove(c.query,a.options),this.chainSend("remove",c)}})),this._publicData.primaryKey(this.privateData().primaryKey()),this._publicData.setData(this.privateData().find())):this._publicData&&(this._publicData.drop(),delete this._publicData,this._transformIo&&(this._transformIo.drop(),delete this._transformIo)),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){return a instanceof l?a:(this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b, count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=l},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":27,"./Shared":29}]},{},[1]);
ajax/libs/react/15.0.0/react-dom-server.js
iwdmb/cdnjs
/** * ReactDOMServer v15.0.0 * * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ // Based off https://github.com/ForbesLindesay/umd/blob/master/template.js ;(function(f) { // CommonJS if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f(require('react')); // RequireJS } else if (typeof define === "function" && define.amd) { define(['react'], f); // <script> } else { var g; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } else { // works providing we're not in "use strict"; // needed for Java 8 Nashorn // see https://github.com/facebook/react/issues/3037 g = this; } g.ReactDOMServer = f(g.React); } })(function(React) { return React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; });
ajax/libs/video.js/5.8.6/alt/video.novtt.js
dc-js/cdnjs
/** * @license * Video.js 5.8.6 <http://videojs.com/> * Copyright Brightcove, Inc. <https://www.brightcove.com/> * Available under Apache License Version 2.0 * <https://github.com/videojs/video.js/blob/master/LICENSE> */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = _dereq_('min-document'); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) //# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvZG9jdW1lbnQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgdG9wTGV2ZWwgPSB0eXBlb2YgZ2xvYmFsICE9PSAndW5kZWZpbmVkJyA/IGdsb2JhbCA6XG4gICAgdHlwZW9mIHdpbmRvdyAhPT0gJ3VuZGVmaW5lZCcgPyB3aW5kb3cgOiB7fVxudmFyIG1pbkRvYyA9IHJlcXVpcmUoJ21pbi1kb2N1bWVudCcpO1xuXG5pZiAodHlwZW9mIGRvY3VtZW50ICE9PSAndW5kZWZpbmVkJykge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZG9jdW1lbnQ7XG59IGVsc2Uge1xuICAgIHZhciBkb2NjeSA9IHRvcExldmVsWydfX0dMT0JBTF9ET0NVTUVOVF9DQUNIRUA0J107XG5cbiAgICBpZiAoIWRvY2N5KSB7XG4gICAgICAgIGRvY2N5ID0gdG9wTGV2ZWxbJ19fR0xPQkFMX0RPQ1VNRU5UX0NBQ0hFQDQnXSA9IG1pbkRvYztcbiAgICB9XG5cbiAgICBtb2R1bGUuZXhwb3J0cyA9IGRvY2N5O1xufVxuIl19 },{"min-document":3}],2:[function(_dereq_,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) //# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvd2luZG93LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsiaWYgKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIpIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHdpbmRvdztcbn0gZWxzZSBpZiAodHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIikge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZ2xvYmFsO1xufSBlbHNlIGlmICh0eXBlb2Ygc2VsZiAhPT0gXCJ1bmRlZmluZWRcIil7XG4gICAgbW9kdWxlLmV4cG9ydHMgPSBzZWxmO1xufSBlbHNlIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHt9O1xufVxuIl19 },{}],3:[function(_dereq_,module,exports){ },{}],4:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeNow = getNative(Date, 'now'); /** * Gets the number of milliseconds that have elapsed since the Unix epoch * (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @category Date * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => logs the number of milliseconds it took for the deferred function to be invoked */ var now = nativeNow || function() { return new Date().getTime(); }; module.exports = now; },{"../internal/getNative":20}],5:[function(_dereq_,module,exports){ var isObject = _dereq_('../lang/isObject'), now = _dereq_('../date/now'); /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed invocations. Provide an options object to indicate that `func` * should be invoked on the leading and/or trailing edge of the `wait` timeout. * Subsequent calls to the debounced function return the result of the last * `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked * on the trailing edge of the timeout only if the the debounced function is * invoked more than once during the `wait` timeout. * * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options] The options object. * @param {boolean} [options.leading=false] Specify invoking on the leading * edge of the timeout. * @param {number} [options.maxWait] The maximum time `func` is allowed to be * delayed before it's invoked. * @param {boolean} [options.trailing=true] Specify invoking on the trailing * edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // avoid costly calculations while the window size is in flux * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // invoke `sendMail` when the click event is fired, debouncing subsequent calls * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // ensure `batchLog` is invoked once after 1 second of debounced calls * var source = new EventSource('/stream'); * jQuery(source).on('message', _.debounce(batchLog, 250, { * 'maxWait': 1000 * })); * * // cancel a debounced call * var todoChanges = _.debounce(batchLog, 1000); * Object.observe(models.todo, todoChanges); * * Object.observe(models, function(changes) { * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { * todoChanges.cancel(); * } * }, ['delete']); * * // ...at some point `models.todo` is changed * models.todo.completed = true; * * // ...before 1 second has passed `models.todo` is deleted * // which cancels the debounced `todoChanges` call * delete models.todo; */ function debounce(func, wait, options) { var args, maxTimeoutId, result, stamp, thisArg, timeoutId, trailingCall, lastCalled = 0, maxWait = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = wait < 0 ? 0 : (+wait || 0); if (options === true) { var leading = true; trailing = false; } else if (isObject(options)) { leading = !!options.leading; maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait); trailing = 'trailing' in options ? !!options.trailing : trailing; } function cancel() { if (timeoutId) { clearTimeout(timeoutId); } if (maxTimeoutId) { clearTimeout(maxTimeoutId); } lastCalled = 0; maxTimeoutId = timeoutId = trailingCall = undefined; } function complete(isCalled, id) { if (id) { clearTimeout(id); } maxTimeoutId = timeoutId = trailingCall = undefined; if (isCalled) { lastCalled = now(); result = func.apply(thisArg, args); if (!timeoutId && !maxTimeoutId) { args = thisArg = undefined; } } } function delayed() { var remaining = wait - (now() - stamp); if (remaining <= 0 || remaining > wait) { complete(trailingCall, maxTimeoutId); } else { timeoutId = setTimeout(delayed, remaining); } } function maxDelayed() { complete(trailing, timeoutId); } function debounced() { args = arguments; stamp = now(); thisArg = this; trailingCall = trailing && (timeoutId || !leading); if (maxWait === false) { var leadingCall = leading && !timeoutId; } else { if (!maxTimeoutId && !leading) { lastCalled = stamp; } var remaining = maxWait - (stamp - lastCalled), isCalled = remaining <= 0 || remaining > maxWait; if (isCalled) { if (maxTimeoutId) { maxTimeoutId = clearTimeout(maxTimeoutId); } lastCalled = stamp; result = func.apply(thisArg, args); } else if (!maxTimeoutId) { maxTimeoutId = setTimeout(maxDelayed, remaining); } } if (isCalled && timeoutId) { timeoutId = clearTimeout(timeoutId); } else if (!timeoutId && wait !== maxWait) { timeoutId = setTimeout(delayed, wait); } if (leadingCall) { isCalled = true; result = func.apply(thisArg, args); } if (isCalled && !timeoutId && !maxTimeoutId) { args = thisArg = undefined; } return result; } debounced.cancel = cancel; return debounced; } module.exports = debounce; },{"../date/now":4,"../lang/isObject":33}],6:[function(_dereq_,module,exports){ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } module.exports = restParam; },{}],7:[function(_dereq_,module,exports){ var debounce = _dereq_('./debounce'), isObject = _dereq_('../lang/isObject'); /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed invocations. Provide an options object to indicate * that `func` should be invoked on the leading and/or trailing edge of the * `wait` timeout. Subsequent calls to the throttled function return the * result of the last `func` call. * * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked * on the trailing edge of the timeout only if the the throttled function is * invoked more than once during the `wait` timeout. * * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options] The options object. * @param {boolean} [options.leading=true] Specify invoking on the leading * edge of the timeout. * @param {boolean} [options.trailing=true] Specify invoking on the trailing * edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // avoid excessively updating the position while scrolling * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { * 'trailing': false * })); * * // cancel a trailing throttled call * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (options === false) { leading = false; } else if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing }); } module.exports = throttle; },{"../lang/isObject":33,"./debounce":5}],8:[function(_dereq_,module,exports){ /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = arrayCopy; },{}],9:[function(_dereq_,module,exports){ /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; },{}],10:[function(_dereq_,module,exports){ /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } module.exports = baseCopy; },{}],11:[function(_dereq_,module,exports){ var createBaseFor = _dereq_('./createBaseFor'); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; },{"./createBaseFor":18}],12:[function(_dereq_,module,exports){ var baseFor = _dereq_('./baseFor'), keysIn = _dereq_('../object/keysIn'); /** * The base implementation of `_.forIn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } module.exports = baseForIn; },{"../object/keysIn":39,"./baseFor":11}],13:[function(_dereq_,module,exports){ var arrayEach = _dereq_('./arrayEach'), baseMergeDeep = _dereq_('./baseMergeDeep'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isObject = _dereq_('../lang/isObject'), isObjectLike = _dereq_('./isObjectLike'), isTypedArray = _dereq_('../lang/isTypedArray'), keys = _dereq_('../object/keys'); /** * The base implementation of `_.merge` without support for argument juggling, * multiple sources, and `this` binding `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [customizer] The function to customize merged values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), props = isSrcArr ? undefined : keys(source); arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } else { var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; } if ((result !== undefined || (isSrcArr && !(key in object))) && (isCommon || (result === result ? (result !== value) : (value === value)))) { object[key] = result; } } }); return object; } module.exports = baseMerge; },{"../lang/isArray":30,"../lang/isObject":33,"../lang/isTypedArray":36,"../object/keys":38,"./arrayEach":9,"./baseMergeDeep":14,"./isArrayLike":21,"./isObjectLike":26}],14:[function(_dereq_,module,exports){ var arrayCopy = _dereq_('./arrayCopy'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isPlainObject = _dereq_('../lang/isPlainObject'), isTypedArray = _dereq_('../lang/isTypedArray'), toPlainObject = _dereq_('../lang/toPlainObject'); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize merged values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { var length = stackA.length, srcValue = source[key]; while (length--) { if (stackA[length] == srcValue) { object[key] = stackB[length]; return; } } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value : (isArrayLike(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) ? toPlainObject(value) : (isPlainObject(value) ? value : {}); } else { isCommon = false; } } // Add the source value to the stack of traversed objects and associate // it with its merged value. stackA.push(srcValue); stackB.push(result); if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); } else if (result === result ? (result !== value) : (value === value)) { object[key] = result; } } module.exports = baseMergeDeep; },{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isPlainObject":34,"../lang/isTypedArray":36,"../lang/toPlainObject":37,"./arrayCopy":8,"./isArrayLike":21}],15:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : toObject(object)[key]; }; } module.exports = baseProperty; },{"./toObject":28}],16:[function(_dereq_,module,exports){ var identity = _dereq_('../utility/identity'); /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } module.exports = bindCallback; },{"../utility/identity":42}],17:[function(_dereq_,module,exports){ var bindCallback = _dereq_('./bindCallback'), isIterateeCall = _dereq_('./isIterateeCall'), restParam = _dereq_('../function/restParam'); /** * Creates a `_.assign`, `_.defaults`, or `_.merge` function. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return restParam(function(object, sources) { var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 ? sources[length - 2] : undefined, guard = length > 2 ? sources[2] : undefined, thisArg = length > 1 ? sources[length - 1] : undefined; if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = typeof thisArg == 'function' ? thisArg : undefined; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } module.exports = createAssigner; },{"../function/restParam":6,"./bindCallback":16,"./isIterateeCall":24}],18:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; },{"./toObject":28}],19:[function(_dereq_,module,exports){ var baseProperty = _dereq_('./baseProperty'); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; },{"./baseProperty":15}],20:[function(_dereq_,module,exports){ var isNative = _dereq_('../lang/isNative'); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } module.exports = getNative; },{"../lang/isNative":32}],21:[function(_dereq_,module,exports){ var getLength = _dereq_('./getLength'), isLength = _dereq_('./isLength'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } module.exports = isArrayLike; },{"./getLength":19,"./isLength":25}],22:[function(_dereq_,module,exports){ /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ var isHostObject = (function() { try { Object({ 'toString': 0 } + ''); } catch(e) { return function() { return false; }; } return function(value) { // IE < 9 presents many host objects as `Object` objects that can coerce // to strings despite having improperly defined `toString` methods. return typeof value.toString != 'function' && typeof (value + '') == 'string'; }; }()); module.exports = isHostObject; },{}],23:[function(_dereq_,module,exports){ /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } module.exports = isIndex; },{}],24:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('./isArrayLike'), isIndex = _dereq_('./isIndex'), isObject = _dereq_('../lang/isObject'); /** * Checks if the provided arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object)) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } module.exports = isIterateeCall; },{"../lang/isObject":33,"./isArrayLike":21,"./isIndex":23}],25:[function(_dereq_,module,exports){ /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; },{}],26:[function(_dereq_,module,exports){ /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; },{}],27:[function(_dereq_,module,exports){ var isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isIndex = _dereq_('./isIndex'), isLength = _dereq_('./isLength'), isString = _dereq_('../lang/isString'), keysIn = _dereq_('../object/keysIn'); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } module.exports = shimKeys; },{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isString":35,"../object/keysIn":39,"./isIndex":23,"./isLength":25}],28:[function(_dereq_,module,exports){ var isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { if (support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); } module.exports = toObject; },{"../lang/isObject":33,"../lang/isString":35,"../support":41}],29:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('../internal/isArrayLike'), isObjectLike = _dereq_('../internal/isObjectLike'); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); } module.exports = isArguments; },{"../internal/isArrayLike":21,"../internal/isObjectLike":26}],30:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var arrayTag = '[object Array]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; module.exports = isArray; },{"../internal/getNative":20,"../internal/isLength":25,"../internal/isObjectLike":26}],31:[function(_dereq_,module,exports){ var isObject = _dereq_('./isObject'); /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 which returns 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } module.exports = isFunction; },{"./isObject":33}],32:[function(_dereq_,module,exports){ var isFunction = _dereq_('./isFunction'), isHostObject = _dereq_('../internal/isHostObject'), isObjectLike = _dereq_('../internal/isObjectLike'); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); } module.exports = isNative; },{"../internal/isHostObject":22,"../internal/isObjectLike":26,"./isFunction":31}],33:[function(_dereq_,module,exports){ /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; },{}],34:[function(_dereq_,module,exports){ var baseForIn = _dereq_('../internal/baseForIn'), isArguments = _dereq_('./isArguments'), isHostObject = _dereq_('../internal/isHostObject'), isObjectLike = _dereq_('../internal/isObjectLike'), support = _dereq_('../support'); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * **Note:** This method assumes objects created by the `Object` constructor * have no inherited enumerable properties. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { var Ctor; // Exit early for non `Object` objects. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value) && !isArguments(value)) || (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { return false; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result; if (support.ownLast) { baseForIn(value, function(subValue, key, object) { result = hasOwnProperty.call(object, key); return false; }); return result !== false; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn(value, function(subValue, key) { result = key; }); return result === undefined || hasOwnProperty.call(value, result); } module.exports = isPlainObject; },{"../internal/baseForIn":12,"../internal/isHostObject":22,"../internal/isObjectLike":26,"../support":41,"./isArguments":29}],35:[function(_dereq_,module,exports){ var isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); } module.exports = isString; },{"../internal/isObjectLike":26}],36:[function(_dereq_,module,exports){ var isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } module.exports = isTypedArray; },{"../internal/isLength":25,"../internal/isObjectLike":26}],37:[function(_dereq_,module,exports){ var baseCopy = _dereq_('../internal/baseCopy'), keysIn = _dereq_('../object/keysIn'); /** * Converts `value` to a plain object flattening inherited enumerable * properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return baseCopy(value, keysIn(value)); } module.exports = toPlainObject; },{"../internal/baseCopy":10,"../object/keysIn":39}],38:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isArrayLike = _dereq_('../internal/isArrayLike'), isObject = _dereq_('../lang/isObject'), shimKeys = _dereq_('../internal/shimKeys'), support = _dereq_('../support'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? undefined : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; module.exports = keys; },{"../internal/getNative":20,"../internal/isArrayLike":21,"../internal/shimKeys":27,"../lang/isObject":33,"../support":41}],39:[function(_dereq_,module,exports){ var arrayEach = _dereq_('../internal/arrayEach'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isFunction = _dereq_('../lang/isFunction'), isIndex = _dereq_('../internal/isIndex'), isLength = _dereq_('../internal/isLength'), isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** `Object#toString` result references. */ var arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** Used to fix the JScript `[[DontEnum]]` bug. */ var shadowProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used for native method references. */ var errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to avoid iterating over non-enumerable properties in IE < 9. */ var nonEnumProps = {}; nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true }; nonEnumProps[objectTag] = { 'constructor': true }; arrayEach(shadowProps, function(key) { for (var tag in nonEnumProps) { if (hasOwnProperty.call(nonEnumProps, tag)) { var props = nonEnumProps[tag]; props[key] = hasOwnProperty.call(props, key); } } }); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)) && length) || 0; var Ctor = object.constructor, index = -1, proto = (isFunction(Ctor) && Ctor.prototype) || objectProto, isProto = proto === object, result = Array(length), skipIndexes = length > 0, skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error), skipProto = support.enumPrototypes && isFunction(object); while (++index < length) { result[index] = (index + ''); } // lodash skips the `constructor` property when it infers it's iterating // over a `prototype` object because IE < 9 can't set the `[[Enumerable]]` // attribute of an existing property and the `constructor` property of a // prototype defaults to non-enumerable. for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name')) && !(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)), nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag]; if (tag == objectTag) { proto = objectProto; } length = shadowProps.length; while (length--) { key = shadowProps[length]; var nonEnum = nonEnums[key]; if (!(isProto && nonEnum) && (nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) { result.push(key); } } } return result; } module.exports = keysIn; },{"../internal/arrayEach":9,"../internal/isIndex":23,"../internal/isLength":25,"../lang/isArguments":29,"../lang/isArray":30,"../lang/isFunction":31,"../lang/isObject":33,"../lang/isString":35,"../support":41}],40:[function(_dereq_,module,exports){ var baseMerge = _dereq_('../internal/baseMerge'), createAssigner = _dereq_('../internal/createAssigner'); /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * overwrite property assignments of previous sources. If `customizer` is * provided it's invoked to produce the merged values of the destination and * source properties. If `customizer` returns `undefined` merging is handled * by the method instead. The `customizer` is bound to `thisArg` and invoked * with five arguments: (objectValue, sourceValue, key, object, source). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } * * // using a customizer callback * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, function(a, b) { * if (_.isArray(a)) { * return a.concat(b); * } * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var merge = createAssigner(baseMerge); module.exports = merge; },{"../internal/baseMerge":13,"../internal/createAssigner":17}],41:[function(_dereq_,module,exports){ /** Used for native method references. */ var arrayProto = Array.prototype, errorProto = Error.prototype, objectProto = Object.prototype; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /** * An object environment feature flags. * * @static * @memberOf _ * @type Object */ var support = {}; (function(x) { var Ctor = function() { this.x = x; }, object = { '0': x, 'length': x }, props = []; Ctor.prototype = { 'valueOf': x, 'y': x }; for (var key in new Ctor) { props.push(key); } /** * Detect if `name` or `message` properties of `Error.prototype` are * enumerable by default (IE < 9, Safari < 5.1). * * @memberOf _.support * @type boolean */ support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly set the `[[Enumerable]]` value of a function's `prototype` * property to `true`. * * @memberOf _.support * @type boolean */ support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype'); /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an object's own properties, shadowing non-enumerable ones, * are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug). * * @memberOf _.support * @type boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if own properties are iterated after inherited properties (IE < 9). * * @memberOf _.support * @type boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `Array#shift` and `Array#splice` augment array-like objects * correctly. * * Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array * `shift()` and `splice()` functions that fail to remove the last element, * `value[0]`, of array-like objects even though the "length" property is * set to `0`. The `shift()` method is buggy in compatibility modes of IE 8, * while `splice()` is buggy regardless of mode in IE < 9. * * @memberOf _.support * @type boolean */ support.spliceObjects = (splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index. IE 8 can only access characters * by index on string literals, not string objects. * * @memberOf _.support * @type boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; }(1, 0)); module.exports = support; },{}],42:[function(_dereq_,module,exports){ /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; },{}],43:[function(_dereq_,module,exports){ 'use strict'; var keys = _dereq_('object-keys'); module.exports = function hasSymbols() { if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } if (typeof Symbol.iterator === 'symbol') { return true; } var obj = {}; var sym = Symbol('test'); if (typeof sym === 'string') { return false; } // temp disabled per https://github.com/ljharb/object.assign/issues/17 // if (sym instanceof Symbol) { return false; } // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 // if (!(Object(sym) instanceof Symbol)) { return false; } var symVal = 42; obj[sym] = symVal; for (sym in obj) { return false; } if (keys(obj).length !== 0) { return false; } if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === 'function') { var descriptor = Object.getOwnPropertyDescriptor(obj, sym); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; },{"object-keys":50}],44:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es6-shim var keys = _dereq_('object-keys'); var bind = _dereq_('function-bind'); var canBeObject = function (obj) { return typeof obj !== 'undefined' && obj !== null; }; var hasSymbols = _dereq_('./hasSymbols')(); var toObject = Object; var push = bind.call(Function.call, Array.prototype.push); var propIsEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable); module.exports = function assign(target, source1) { if (!canBeObject(target)) { throw new TypeError('target must be an object'); } var objTarget = toObject(target); var s, source, i, props, syms, value, key; for (s = 1; s < arguments.length; ++s) { source = toObject(arguments[s]); props = keys(source); if (hasSymbols && Object.getOwnPropertySymbols) { syms = Object.getOwnPropertySymbols(source); for (i = 0; i < syms.length; ++i) { key = syms[i]; if (propIsEnumerable(source, key)) { push(props, key); } } } for (i = 0; i < props.length; ++i) { key = props[i]; value = source[key]; if (propIsEnumerable(source, key)) { objTarget[key] = value; } } } return objTarget; }; },{"./hasSymbols":43,"function-bind":49,"object-keys":50}],45:[function(_dereq_,module,exports){ 'use strict'; var defineProperties = _dereq_('define-properties'); var implementation = _dereq_('./implementation'); var getPolyfill = _dereq_('./polyfill'); var shim = _dereq_('./shim'); defineProperties(implementation, { implementation: implementation, getPolyfill: getPolyfill, shim: shim }); module.exports = implementation; },{"./implementation":44,"./polyfill":52,"./shim":53,"define-properties":46}],46:[function(_dereq_,module,exports){ 'use strict'; var keys = _dereq_('object-keys'); var foreach = _dereq_('foreach'); var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var toStr = Object.prototype.toString; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { Object.defineProperty(obj, 'x', { enumerable: false, value: obj }); /* eslint-disable no-unused-vars, no-restricted-syntax */ for (var _ in obj) { return false; } /* eslint-enable no-unused-vars, no-restricted-syntax */ return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, value: value, writable: true }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = props.concat(Object.getOwnPropertySymbols(map)); } foreach(props, function (name) { defineProperty(object, name, map[name], predicates[name]); }); }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; },{"foreach":47,"object-keys":50}],47:[function(_dereq_,module,exports){ var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; },{}],48:[function(_dereq_,module,exports){ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; },{}],49:[function(_dereq_,module,exports){ var implementation = _dereq_('./implementation'); module.exports = Function.prototype.bind || implementation; },{"./implementation":48}],50:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = _dereq_('./isArguments'); var hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var blacklistedKeys = { $console: true, $frame: true, $frameElement: true, $frames: true, $parent: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; },{"./isArguments":51}],51:[function(_dereq_,module,exports){ 'use strict'; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; },{}],52:[function(_dereq_,module,exports){ 'use strict'; var implementation = _dereq_('./implementation'); var lacksProperEnumerationOrder = function () { if (!Object.assign) { return false; } // v8, specifically in node 4.x, has a bug with incorrect property enumeration order // note: this does not detect the bug unless there's 20 characters var str = 'abcdefghijklmnopqrst'; var letters = str.split(''); var map = {}; for (var i = 0; i < letters.length; ++i) { map[letters[i]] = letters[i]; } var obj = Object.assign({}, map); var actual = ''; for (var k in obj) { actual += k; } return str !== actual; }; var assignHasPendingExceptions = function () { if (!Object.assign || !Object.preventExtensions) { return false; } // Firefox 37 still has "pending exception" logic in its Object.assign implementation, // which is 72% slower than our shim, and Firefox 40's native implementation. var thrower = Object.preventExtensions({ 1: 2 }); try { Object.assign(thrower, 'xy'); } catch (e) { return thrower[1] === 'y'; } }; module.exports = function getPolyfill() { if (!Object.assign) { return implementation; } if (lacksProperEnumerationOrder()) { return implementation; } if (assignHasPendingExceptions()) { return implementation; } return Object.assign; }; },{"./implementation":44}],53:[function(_dereq_,module,exports){ 'use strict'; var define = _dereq_('define-properties'); var getPolyfill = _dereq_('./polyfill'); module.exports = function shimAssign() { var polyfill = getPolyfill(); define( Object, { assign: polyfill }, { assign: function () { return Object.assign !== polyfill; } } ); return polyfill; }; },{"./polyfill":52,"define-properties":46}],54:[function(_dereq_,module,exports){ module.exports = SafeParseTuple function SafeParseTuple(obj, reviver) { var json var error = null try { json = JSON.parse(obj, reviver) } catch (err) { error = err } return [error, json] } },{}],55:[function(_dereq_,module,exports){ function clean (s) { return s.replace(/\n\r?\s*/g, '') } module.exports = function tsml (sa) { var s = '' , i = 0 for (; i < arguments.length; i++) s += clean(sa[i]) + (arguments[i + 1] || '') return s } },{}],56:[function(_dereq_,module,exports){ "use strict"; var window = _dereq_("global/window") var once = _dereq_("once") var isFunction = _dereq_("is-function") var parseHeaders = _dereq_("parse-headers") var xtend = _dereq_("xtend") module.exports = createXHR createXHR.XMLHttpRequest = window.XMLHttpRequest || noop createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) { createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) { options = initParams(uri, options, callback) options.method = method.toUpperCase() return _createXHR(options) } }) function forEachArray(array, iterator) { for (var i = 0; i < array.length; i++) { iterator(array[i]) } } function isEmpty(obj){ for(var i in obj){ if(obj.hasOwnProperty(i)) return false } return true } function initParams(uri, options, callback) { var params = uri if (isFunction(options)) { callback = options if (typeof uri === "string") { params = {uri:uri} } } else { params = xtend(options, {uri: uri}) } params.callback = callback return params } function createXHR(uri, options, callback) { options = initParams(uri, options, callback) return _createXHR(options) } function _createXHR(options) { var callback = options.callback if(typeof callback === "undefined"){ throw new Error("callback argument missing") } callback = once(callback) function readystatechange() { if (xhr.readyState === 4) { loadFunc() } } function getBody() { // Chrome with requestType=blob throws errors arround when even testing access to responseText var body = undefined if (xhr.response) { body = xhr.response } else if (xhr.responseType === "text" || !xhr.responseType) { body = xhr.responseText || xhr.responseXML } if (isJson) { try { body = JSON.parse(body) } catch (e) {} } return body } var failureResponse = { body: undefined, headers: {}, statusCode: 0, method: method, url: uri, rawRequest: xhr } function errorFunc(evt) { clearTimeout(timeoutTimer) if(!(evt instanceof Error)){ evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) } evt.statusCode = 0 callback(evt, failureResponse) } // will load the data & process the response in a special response object function loadFunc() { if (aborted) return var status clearTimeout(timeoutTimer) if(options.useXDR && xhr.status===undefined) { //IE8 CORS GET successful response doesn't have a status field, but body is fine status = 200 } else { status = (xhr.status === 1223 ? 204 : xhr.status) } var response = failureResponse var err = null if (status !== 0){ response = { body: getBody(), statusCode: status, method: method, headers: {}, url: uri, rawRequest: xhr } if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE response.headers = parseHeaders(xhr.getAllResponseHeaders()) } } else { err = new Error("Internal XMLHttpRequest Error") } callback(err, response, response.body) } var xhr = options.xhr || null if (!xhr) { if (options.cors || options.useXDR) { xhr = new createXHR.XDomainRequest() }else{ xhr = new createXHR.XMLHttpRequest() } } var key var aborted var uri = xhr.url = options.uri || options.url var method = xhr.method = options.method || "GET" var body = options.body || options.data || null var headers = xhr.headers = options.headers || {} var sync = !!options.sync var isJson = false var timeoutTimer if ("json" in options) { isJson = true headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user if (method !== "GET" && method !== "HEAD") { headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user body = JSON.stringify(options.json) } } xhr.onreadystatechange = readystatechange xhr.onload = loadFunc xhr.onerror = errorFunc // IE9 must have onprogress be set to a unique function. xhr.onprogress = function () { // IE must die } xhr.ontimeout = errorFunc xhr.open(method, uri, !sync, options.username, options.password) //has to be after open if(!sync) { xhr.withCredentials = !!options.withCredentials } // Cannot set timeout with sync request // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent if (!sync && options.timeout > 0 ) { timeoutTimer = setTimeout(function(){ aborted=true//IE9 may still call readystatechange xhr.abort("timeout") var e = new Error("XMLHttpRequest timeout") e.code = "ETIMEDOUT" errorFunc(e) }, options.timeout ) } if (xhr.setRequestHeader) { for(key in headers){ if(headers.hasOwnProperty(key)){ xhr.setRequestHeader(key, headers[key]) } } } else if (options.headers && !isEmpty(options.headers)) { throw new Error("Headers cannot be set on an XDomainRequest object") } if ("responseType" in options) { xhr.responseType = options.responseType } if ("beforeSend" in options && typeof options.beforeSend === "function" ) { options.beforeSend(xhr) } xhr.send(body) return xhr } function noop() {} },{"global/window":2,"is-function":57,"once":58,"parse-headers":61,"xtend":62}],57:[function(_dereq_,module,exports){ module.exports = isFunction var toString = Object.prototype.toString function isFunction (fn) { var string = toString.call(fn) return string === '[object Function]' || (typeof fn === 'function' && string !== '[object RegExp]') || (typeof window !== 'undefined' && // IE8 and below (fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt)) }; },{}],58:[function(_dereq_,module,exports){ module.exports = once once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) }) function once (fn) { var called = false return function () { if (called) return called = true return fn.apply(this, arguments) } } },{}],59:[function(_dereq_,module,exports){ var isFunction = _dereq_('is-function') module.exports = forEach var toString = Object.prototype.toString var hasOwnProperty = Object.prototype.hasOwnProperty function forEach(list, iterator, context) { if (!isFunction(iterator)) { throw new TypeError('iterator must be a function') } if (arguments.length < 3) { context = this } if (toString.call(list) === '[object Array]') forEachArray(list, iterator, context) else if (typeof list === 'string') forEachString(list, iterator, context) else forEachObject(list, iterator, context) } function forEachArray(array, iterator, context) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { iterator.call(context, array[i], i, array) } } } function forEachString(string, iterator, context) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. iterator.call(context, string.charAt(i), i, string) } } function forEachObject(object, iterator, context) { for (var k in object) { if (hasOwnProperty.call(object, k)) { iterator.call(context, object[k], k, object) } } } },{"is-function":57}],60:[function(_dereq_,module,exports){ exports = module.exports = trim; function trim(str){ return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ return str.replace(/^\s*/, ''); }; exports.right = function(str){ return str.replace(/\s*$/, ''); }; },{}],61:[function(_dereq_,module,exports){ var trim = _dereq_('trim') , forEach = _dereq_('for-each') , isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; } module.exports = function (headers) { if (!headers) return {} var result = {} forEach( trim(headers).split('\n') , function (row) { var index = row.indexOf(':') , key = trim(row.slice(0, index)).toLowerCase() , value = trim(row.slice(index + 1)) if (typeof(result[key]) === 'undefined') { result[key] = value } else if (isArray(result[key])) { result[key].push(value) } else { result[key] = [ result[key], value ] } } ) return result } },{"for-each":59,"trim":60}],62:[function(_dereq_,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } },{}],63:[function(_dereq_,module,exports){ /** * @file big-play-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('./button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Button * @class BigPlayButton */ var BigPlayButton = (function (_Button) { _inherits(BigPlayButton, _Button); function BigPlayButton(player, options) { _classCallCheck(this, BigPlayButton); _Button.call(this, player, options); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ BigPlayButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-big-play-button'; }; /** * Handles click for play * * @method handleClick */ BigPlayButton.prototype.handleClick = function handleClick() { this.player_.play(); }; return BigPlayButton; })(_buttonJs2['default']); BigPlayButton.prototype.controlText_ = 'Play Video'; _componentJs2['default'].registerComponent('BigPlayButton', BigPlayButton); exports['default'] = BigPlayButton; module.exports = exports['default']; },{"./button.js":64,"./component.js":67}],64:[function(_dereq_,module,exports){ /** * @file button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _clickableComponentJs = _dereq_('./clickable-component.js'); var _clickableComponentJs2 = _interopRequireDefault(_clickableComponentJs); var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * Base class for all buttons * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends ClickableComponent * @class Button */ var Button = (function (_ClickableComponent) { _inherits(Button, _ClickableComponent); function Button(player, options) { _classCallCheck(this, Button); _ClickableComponent.call(this, player, options); } /** * Create the component's DOM element * * @param {String=} type Element's node type. e.g. 'div' * @param {Object=} props An object of properties that should be set on the element * @param {Object=} attributes An object of attributes that should be set on the element * @return {Element} * @method createEl */ Button.prototype.createEl = function createEl() { var tag = arguments.length <= 0 || arguments[0] === undefined ? 'button' : arguments[0]; var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; props = _objectAssign2['default']({ className: this.buildCSSClass() }, props); if (tag !== 'button') { _utilsLogJs2['default'].warn('Creating a Button with an HTML element of ' + tag + ' is deprecated; use ClickableComponent instead.'); } // Add attributes for button element attributes = _objectAssign2['default']({ type: 'button', // Necessary since the default button type is "submit" 'aria-live': 'polite' // let the screen reader user know that the text of the button may change }, attributes); var el = _component2['default'].prototype.createEl.call(this, tag, props, attributes); this.createControlTextEl(el); return el; }; /** * Adds a child component inside this button * * @param {String|Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {Component} The child component (created by this process if a string was used) * @deprecated * @method addChild */ Button.prototype.addChild = function addChild(child) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var className = this.constructor.name; _utilsLogJs2['default'].warn('Adding an actionable (user controllable) child to a Button (' + className + ') is not supported; use a ClickableComponent instead.'); // Avoid the error message generated by ClickableComponent's addChild method return _component2['default'].prototype.addChild.call(this, child, options); }; /** * Handle KeyPress (document level) - Extend with specific functionality for button * * @method handleKeyPress */ Button.prototype.handleKeyPress = function handleKeyPress(event) { // Ignore Space (32) or Enter (13) key operation, which is handled by the browser for a button. if (event.which === 32 || event.which === 13) {} else { _ClickableComponent.prototype.handleKeyPress.call(this, event); // Pass keypress handling up for unsupported keys } }; return Button; })(_clickableComponentJs2['default']); _component2['default'].registerComponent('Button', Button); exports['default'] = Button; module.exports = exports['default']; },{"./clickable-component.js":65,"./component":67,"./utils/events.js":133,"./utils/fn.js":134,"./utils/log.js":137,"global/document":1,"object.assign":45}],65:[function(_dereq_,module,exports){ /** * @file button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * Clickable Component which is clickable or keyboard actionable, but is not a native HTML button * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class ClickableComponent */ var ClickableComponent = (function (_Component) { _inherits(ClickableComponent, _Component); function ClickableComponent(player, options) { _classCallCheck(this, ClickableComponent); _Component.call(this, player, options); this.emitTapEvents(); this.on('tap', this.handleClick); this.on('click', this.handleClick); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); } /** * Create the component's DOM element * * @param {String=} type Element's node type. e.g. 'div' * @param {Object=} props An object of properties that should be set on the element * @param {Object=} attributes An object of attributes that should be set on the element * @return {Element} * @method createEl */ ClickableComponent.prototype.createEl = function createEl() { var tag = arguments.length <= 0 || arguments[0] === undefined ? 'div' : arguments[0]; var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; props = _objectAssign2['default']({ className: this.buildCSSClass(), tabIndex: 0 }, props); if (tag === 'button') { _utilsLogJs2['default'].error('Creating a ClickableComponent with an HTML element of ' + tag + ' is not supported; use a Button instead.'); } // Add ARIA attributes for clickable element which is not a native HTML button attributes = _objectAssign2['default']({ role: 'button', 'aria-live': 'polite' // let the screen reader user know that the text of the element may change }, attributes); var el = _Component.prototype.createEl.call(this, tag, props, attributes); this.createControlTextEl(el); return el; }; /** * create control text * * @param {Element} el Parent element for the control text * @return {Element} * @method controlText */ ClickableComponent.prototype.createControlTextEl = function createControlTextEl(el) { this.controlTextEl_ = Dom.createEl('span', { className: 'vjs-control-text' }); if (el) { el.appendChild(this.controlTextEl_); } this.controlText(this.controlText_); return this.controlTextEl_; }; /** * Controls text - both request and localize * * @param {String} text Text for element * @return {String} * @method controlText */ ClickableComponent.prototype.controlText = function controlText(text) { if (!text) return this.controlText_ || 'Need Text'; this.controlText_ = text; this.controlTextEl_.innerHTML = this.localize(this.controlText_); return this; }; /** * Allows sub components to stack CSS class names * * @return {String} * @method buildCSSClass */ ClickableComponent.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this); }; /** * Adds a child component inside this clickable-component * * @param {String|Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {Component} The child component (created by this process if a string was used) * @method addChild */ ClickableComponent.prototype.addChild = function addChild(child) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; // TODO: Fix adding an actionable child to a ClickableComponent; currently // it will cause issues with assistive technology (e.g. screen readers) // which support ARIA, since an element with role="button" cannot have // actionable child elements. //let className = this.constructor.name; //log.warn(`Adding a child to a ClickableComponent (${className}) can cause issues with assistive technology which supports ARIA, since an element with role="button" cannot have actionable child elements.`); return _Component.prototype.addChild.call(this, child, options); }; /** * Handle Click - Override with specific functionality for component * * @method handleClick */ ClickableComponent.prototype.handleClick = function handleClick() {}; /** * Handle Focus - Add keyboard functionality to element * * @method handleFocus */ ClickableComponent.prototype.handleFocus = function handleFocus() { Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; /** * Handle KeyPress (document level) - Trigger click when Space or Enter key is pressed * * @method handleKeyPress */ ClickableComponent.prototype.handleKeyPress = function handleKeyPress(event) { // Support Space (32) or Enter (13) key operation to fire a click event if (event.which === 32 || event.which === 13) { event.preventDefault(); this.handleClick(event); } else if (_Component.prototype.handleKeyPress) { _Component.prototype.handleKeyPress.call(this, event); // Pass keypress handling up for unsupported keys } }; /** * Handle Blur - Remove keyboard triggers * * @method handleBlur */ ClickableComponent.prototype.handleBlur = function handleBlur() { Events.off(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; return ClickableComponent; })(_component2['default']); _component2['default'].registerComponent('ClickableComponent', ClickableComponent); exports['default'] = ClickableComponent; module.exports = exports['default']; },{"./component":67,"./utils/dom.js":132,"./utils/events.js":133,"./utils/fn.js":134,"./utils/log.js":137,"global/document":1,"object.assign":45}],66:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _button = _dereq_('./button'); var _button2 = _interopRequireDefault(_button); var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); /** * The `CloseButton` component is a button which fires a "close" event * when it is activated. * * @extends Button * @class CloseButton */ var CloseButton = (function (_Button) { _inherits(CloseButton, _Button); function CloseButton(player, options) { _classCallCheck(this, CloseButton); _Button.call(this, player, options); this.controlText(options && options.controlText || this.localize('Close')); } CloseButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-close-button ' + _Button.prototype.buildCSSClass.call(this); }; CloseButton.prototype.handleClick = function handleClick() { this.trigger({ type: 'close', bubbles: false }); }; return CloseButton; })(_button2['default']); _component2['default'].registerComponent('CloseButton', CloseButton); exports['default'] = CloseButton; module.exports = exports['default']; },{"./button":64,"./component":67}],67:[function(_dereq_,module,exports){ /** * @file component.js * * Player Component - Base class for all UI objects */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); /** * Base UI Component class * Components are embeddable UI objects that are represented by both a * javascript object and an element in the DOM. They can be children of other * components, and can have many children themselves. * ```js * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * ``` * ```html * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * ``` * Components are also event targets. * ```js * button.on('click', function(){ * console.log('Button Clicked!'); * }); * button.trigger('customevent'); * ``` * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @class Component */ var Component = (function () { function Component(player, options, ready) { _classCallCheck(this, Component); // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = _utilsMergeOptionsJs2['default']({}, this.options_); // Updated options with supplied options options = this.options_ = _utilsMergeOptionsJs2['default'](this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = id + '_component_' + Guid.newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } /** * Dispose of the component and all child components * * @method dispose */ Component.prototype.dispose = function dispose() { this.trigger({ type: 'dispose', bubbles: false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } Dom.removeElData(this.el_); this.el_ = null; }; /** * Return the component's player * * @return {Player} * @method player */ Component.prototype.player = function player() { return this.player_; }; /** * Deep merge of options objects * Whenever a property is an object on both options objects * the two properties will be merged using mergeOptions. * * ```js * Parent.prototype.options_ = { * optionSet: { * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childTwo': {}, * 'childThree': {} * } * } * newOptions = { * optionSet: { * 'childOne': { 'foo': 'baz', 'abc': '123' } * 'childTwo': null, * 'childFour': {} * } * } * * this.options(newOptions); * ``` * RESULT * ```js * { * optionSet: { * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childTwo': null, // Disabled. Won't be initialized. * 'childThree': {}, * 'childFour': {} * } * } * ``` * * @param {Object} obj Object of new option values * @return {Object} A NEW object of this.options_ and obj merged * @method options */ Component.prototype.options = function options(obj) { _utilsLogJs2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0'); if (!obj) { return this.options_; } this.options_ = _utilsMergeOptionsJs2['default'](this.options_, obj); return this.options_; }; /** * Get the component's DOM element * ```js * var domEl = myComponent.el(); * ``` * * @return {Element} * @method el */ Component.prototype.el = function el() { return this.el_; }; /** * Create the component's DOM element * * @param {String=} tagName Element's node type. e.g. 'div' * @param {Object=} properties An object of properties that should be set * @param {Object=} attributes An object of attributes that should be set * @return {Element} * @method createEl */ Component.prototype.createEl = function createEl(tagName, properties, attributes) { return Dom.createEl(tagName, properties, attributes); }; Component.prototype.localize = function localize(string) { var code = this.player_.language && this.player_.language(); var languages = this.player_.languages && this.player_.languages(); if (!code || !languages) { return string; } var language = languages[code]; if (language && language[string]) { return language[string]; } var primaryCode = code.split('-')[0]; var primaryLang = languages[primaryCode]; if (primaryLang && primaryLang[string]) { return primaryLang[string]; } return string; }; /** * Return the component's DOM element where children are inserted. * Will either be the same as el() or a new element defined in createEl(). * * @return {Element} * @method contentEl */ Component.prototype.contentEl = function contentEl() { return this.contentEl_ || this.el_; }; /** * Get the component's ID * ```js * var id = myComponent.id(); * ``` * * @return {String} * @method id */ Component.prototype.id = function id() { return this.id_; }; /** * Get the component's name. The name is often used to reference the component. * ```js * var name = myComponent.name(); * ``` * * @return {String} * @method name */ Component.prototype.name = function name() { return this.name_; }; /** * Get an array of all child components * ```js * var kids = myComponent.children(); * ``` * * @return {Array} The children * @method children */ Component.prototype.children = function children() { return this.children_; }; /** * Returns a child component with the provided ID * * @return {Component} * @method getChildById */ Component.prototype.getChildById = function getChildById(id) { return this.childIndex_[id]; }; /** * Returns a child component with the provided name * * @return {Component} * @method getChild */ Component.prototype.getChild = function getChild(name) { return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * ```js * myComponent.el(); * // -> <div class='my-component'></div> * myComponent.children(); * // [empty array] * * var myButton = myComponent.addChild('MyButton'); * // -> <div class='my-component'><div class="my-button">myButton<div></div> * // -> myButton === myComponent.children()[0]; * ``` * Pass in options for child constructors and options for children of the child * ```js * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * buttonChildExample: { * buttonChildOption: true * } * }); * ``` * * @param {String|Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @param {Number} index into our children array to attempt to add the child * @return {Component} The child component (created by this process if a string was used) * @method addChild */ Component.prototype.addChild = function addChild(child) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var index = arguments.length <= 2 || arguments[2] === undefined ? this.children_.length : arguments[2]; var component = undefined; var componentName = undefined; // If child is a string, create nt with options if (typeof child === 'string') { componentName = child; // Options can also be specified as a boolean, so convert to an empty object if false. if (!options) { options = {}; } // Same as above, but true is deprecated so show a warning. if (options === true) { _utilsLogJs2['default'].warn('Initializing a child component with `true` is deprecated. Children should be defined in an array when possible, but if necessary use an object instead of `true`.'); options = {}; } // If no componentClass in options, assume componentClass is the name lowercased // (e.g. playButton) var componentClassName = options.componentClass || _utilsToTitleCaseJs2['default'](componentName); // Set name through options options.name = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player var ComponentClass = Component.getComponent(componentClassName); if (!ComponentClass) { throw new Error('Component ' + componentClassName + ' does not exist'); } // data stored directly on the videojs object may be // misidentified as a component to retain // backwards-compatibility with 4.x. check to make sure the // component class can be instantiated. if (typeof ComponentClass !== 'function') { return null; } component = new ComponentClass(this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.splice(index, 0, component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || component.name && component.name(); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component.el === 'function' && component.el()) { var childNodes = this.contentEl().children; var refNode = childNodes[index] || null; this.contentEl().insertBefore(component.el(), refNode); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {Component} component Component to remove * @method removeChild */ Component.prototype.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) { return; } var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i, 1); break; } } if (!childFound) { return; } this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child components from options * ```js * // when an instance of MyComponent is created, all children in options * // will be added to the instance by their name strings and options * MyComponent.prototype.options_ = { * children: [ * 'myChildComponent' * ], * myChildComponent: { * myChildOption: true * } * }; * * // Or when creating the component * var myComp = new MyComponent(player, { * children: [ * 'myChildComponent' * ], * myChildComponent: { * myChildOption: true * } * }); * ``` * The children option can also be an array of * child options objects (that also include a 'name' key). * This can be used if you have two child components of the * same type that need different options. * ```js * var myComp = new MyComponent(player, { * children: [ * 'button', * { * name: 'button', * someOtherOption: true * }, * { * name: 'button', * someOtherOption: false * } * ] * }); * ``` * * @method initChildren */ Component.prototype.initChildren = function initChildren() { var _this = this; var children = this.options_.children; if (children) { (function () { // `this` is `parent` var parentOptions = _this.options_; var handleAdd = function handleAdd(child) { var name = child.name; var opts = child.opts; // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. options['children']['posterImage'] = false if (opts === false) { return; } // Allow options to be passed as a simple boolean if no configuration // is necessary. if (opts === true) { opts = {}; } // We also want to pass the original player options to each component as well so they don't need to // reach back into the player for options later. opts.playerOptions = _this.options_.playerOptions; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each var newChild = _this.addChild(name, opts); if (newChild) { _this[name] = newChild; } }; // Allow for an array of children details to passed in the options var workingChildren = undefined; var Tech = Component.getComponent('Tech'); if (Array.isArray(children)) { workingChildren = children; } else { workingChildren = Object.keys(children); } workingChildren // children that are in this.options_ but also in workingChildren would // give us extra children we do not want. So, we want to filter them out. .concat(Object.keys(_this.options_).filter(function (child) { return !workingChildren.some(function (wchild) { if (typeof wchild === 'string') { return child === wchild; } else { return child === wchild.name; } }); })).map(function (child) { var name = undefined, opts = undefined; if (typeof child === 'string') { name = child; opts = children[name] || _this.options_[name] || {}; } else { name = child.name; opts = child; } return { name: name, opts: opts }; }).filter(function (child) { // we have to make sure that child.name isn't in the techOrder since // techs are registerd as Components but can't aren't compatible // See https://github.com/videojs/video.js/issues/2772 var c = Component.getComponent(child.opts.componentClass || _utilsToTitleCaseJs2['default'](child.name)); return c && !Tech.isTech(c); }).forEach(handleAdd); })(); } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Component.prototype.buildCSSClass = function buildCSSClass() { // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /** * Add an event listener to this component's element * ```js * var myFunc = function(){ * var myComponent = this; * // Do something when the event is fired * }; * * myComponent.on('eventType', myFunc); * ``` * The context of myFunc will be myComponent unless previously bound. * Alternatively, you can add a listener to another element or component. * ```js * myComponent.on(otherElement, 'eventName', myFunc); * myComponent.on(otherComponent, 'eventName', myFunc); * ``` * The benefit of using this over `VjsEvents.on(otherElement, 'eventName', myFunc)` * and `otherComponent.on('eventName', myFunc)` is that this way the listeners * will be automatically cleaned up when either component is disposed. * It will also bind myComponent as the context of myFunc. * **NOTE**: When using this on elements in the page other than window * and document (both permanent), if you remove the element from the DOM * you need to call `myComponent.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {String|Component} first The event type or other component * @param {Function|String} second The event handler or event type * @param {Function} third The event handler * @return {Component} * @method on */ Component.prototype.on = function on(first, second, third) { var _this2 = this; if (typeof first === 'string' || Array.isArray(first)) { Events.on(this.el_, first, Fn.bind(this, second)); // Targeting another component or element } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this2, third); // When this component is disposed, remove the listener from the other component var removeOnDispose = function removeOnDispose() { return _this2.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; _this2.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. var cleanRemover = function cleanRemover() { return _this2.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element Events.on(target, type, fn); Events.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } })(); } return this; }; /** * Remove an event listener from this component's element * ```js * myComponent.off('eventType', myFunc); * ``` * If myFunc is excluded, ALL listeners for the event type will be removed. * If eventType is excluded, ALL listeners will be removed from the component. * Alternatively you can use `off` to remove listeners that were added to other * elements or components using `myComponent.on(otherComponent...`. * In this case both the event type and listener function are REQUIRED. * ```js * myComponent.off(otherElement, 'eventType', myFunc); * myComponent.off(otherComponent, 'eventType', myFunc); * ``` * * @param {String=|Component} first The event type or other component * @param {Function=|String} second The listener function or event type * @param {Function=} third The listener for other component * @return {Component} * @method off */ Component.prototype.off = function off(first, second, third) { if (!first || typeof first === 'string' || Array.isArray(first)) { Events.off(this.el_, first, second); } else { var target = first; var type = second; // Ensure there's at least a guid, even if the function hasn't been used var fn = Fn.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener Events.off(target, type, fn); // Remove the listener for cleaning the dispose listener Events.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener to be triggered only once and then removed * ```js * myComponent.one('eventName', myFunc); * ``` * Alternatively you can add a listener to another element or component * that will be triggered only once. * ```js * myComponent.one(otherElement, 'eventName', myFunc); * myComponent.one(otherComponent, 'eventName', myFunc); * ``` * * @param {String|Component} first The event type or other component * @param {Function|String} second The listener function or event type * @param {Function=} third The listener function for other component * @return {Component} * @method one */ Component.prototype.one = function one(first, second, third) { var _this3 = this, _arguments = arguments; if (typeof first === 'string' || Array.isArray(first)) { Events.one(this.el_, first, Fn.bind(this, second)); } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this3, third); var newFunc = function newFunc() { _this3.off(target, type, newFunc); fn.apply(null, _arguments); }; // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; _this3.on(target, type, newFunc); })(); } return this; }; /** * Trigger an event on an element * ```js * myComponent.trigger('eventName'); * myComponent.trigger({'type':'eventName'}); * myComponent.trigger('eventName', {data: 'some data'}); * myComponent.trigger({'type':'eventName'}, {data: 'some data'}); * ``` * * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Component} self * @method trigger */ Component.prototype.trigger = function trigger(event, hash) { Events.trigger(this.el_, event, hash); return this; }; /** * Bind a listener to the component's ready state. * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @param {Function} fn Ready listener * @param {Boolean} sync Exec the listener synchronously if component is ready * @return {Component} * @method ready */ Component.prototype.ready = function ready(fn) { var sync = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; if (fn) { if (this.isReady_) { if (sync) { fn.call(this); } else { // Call the function asynchronously by default for consistency this.setTimeout(fn, 1); } } else { this.readyQueue_ = this.readyQueue_ || []; this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {Component} * @method triggerReady */ Component.prototype.triggerReady = function triggerReady() { this.isReady_ = true; // Ensure ready is triggerd asynchronously this.setTimeout(function () { var readyQueue = this.readyQueue_; // Reset Ready Queue this.readyQueue_ = []; if (readyQueue && readyQueue.length > 0) { readyQueue.forEach(function (fn) { fn.call(this); }, this); } // Allow for using event listeners also this.trigger('ready'); }, 1); }; /** * Finds a single DOM element matching `selector` within the component's * `contentEl` or another custom context. * * @method $ * @param {String} selector * A valid CSS selector, which will be passed to `querySelector`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {Element|null} */ Component.prototype.$ = function $(selector, context) { return Dom.$(selector, context || this.contentEl()); }; /** * Finds a all DOM elements matching `selector` within the component's * `contentEl` or another custom context. * * @method $$ * @param {String} selector * A valid CSS selector, which will be passed to `querySelectorAll`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {NodeList} */ Component.prototype.$$ = function $$(selector, context) { return Dom.$$(selector, context || this.contentEl()); }; /** * Check if a component's element has a CSS class name * * @param {String} classToCheck Classname to check * @return {Component} * @method hasClass */ Component.prototype.hasClass = function hasClass(classToCheck) { return Dom.hasElClass(this.el_, classToCheck); }; /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {Component} * @method addClass */ Component.prototype.addClass = function addClass(classToAdd) { Dom.addElClass(this.el_, classToAdd); return this; }; /** * Remove a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {Component} * @method removeClass */ Component.prototype.removeClass = function removeClass(classToRemove) { Dom.removeElClass(this.el_, classToRemove); return this; }; /** * Add or remove a CSS class name from the component's element * * @param {String} classToToggle * @param {Boolean|Function} [predicate] * Can be a function that returns a Boolean. If `true`, the class * will be added; if `false`, the class will be removed. If not * given, the class will be added if not present and vice versa. * * @return {Component} * @method toggleClass */ Component.prototype.toggleClass = function toggleClass(classToToggle, predicate) { Dom.toggleElClass(this.el_, classToToggle, predicate); return this; }; /** * Show the component element if hidden * * @return {Component} * @method show */ Component.prototype.show = function show() { this.removeClass('vjs-hidden'); return this; }; /** * Hide the component element if currently showing * * @return {Component} * @method hide */ Component.prototype.hide = function hide() { this.addClass('vjs-hidden'); return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method lockShowing */ Component.prototype.lockShowing = function lockShowing() { this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method unlockShowing */ Component.prototype.unlockShowing = function unlockShowing() { this.removeClass('vjs-lock-showing'); return this; }; /** * Set or get the width of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num Optional width number * @param {Boolean} skipListeners Skip the 'resize' event trigger * @return {Component} This component, when setting the width * @return {Number|String} The width, when getting * @method width */ Component.prototype.width = function width(num, skipListeners) { return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num New component height * @param {Boolean=} skipListeners Skip the resize event trigger * @return {Component} This component, when setting the height * @return {Number|String} The height, when getting * @method height */ Component.prototype.height = function height(num, skipListeners) { return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width Width of player * @param {Number|String} height Height of player * @return {Component} The component * @method dimensions */ Component.prototype.dimensions = function dimensions(width, height) { // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height * This is the shared code for the width() and height() methods. * All for an integer, integer + 'px' or integer + '%'; * Known issue: Hidden elements officially have a width of 0. We're defaulting * to the style.width value and falling back to computedStyle which has the * hidden element issue. Info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {String} widthOrHeight 'width' or 'height' * @param {Number|String=} num New dimension * @param {Boolean=} skipListeners Skip resize event trigger * @return {Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private * @method dimension */ Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) { if (num !== undefined) { // Set to zero if null or literally NaN (NaN !== NaN) if (num === null || num !== num) { num = 0; } // Check if using css width/height (% or px) and adjust if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num + 'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) { return 0; } // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0, pxIndex), 10); } // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px return parseInt(this.el_['offset' + _utilsToTitleCaseJs2['default'](widthOrHeight)], 10); }; /** * Emit 'tap' events when touch events are supported * This is used to support toggling the controls through a tap on the video. * We're requiring them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * * @private * @method emitTapEvents */ Component.prototype.emitTapEvents = function emitTapEvents() { // Track the start time so we can determine how long the touch lasted var touchStart = 0; var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap var touchTimeThreshold = 200; var couldBeTap = undefined; this.on('touchstart', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { // Copy the touches object to prevent modifying the original firstTouch = _objectAssign2['default']({}, event.touches[0]); // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap var xdiff = event.touches[0].pageX - firstTouch.pageX; var ydiff = event.touches[0].pageY - firstTouch.pageY; var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); var noTap = function noTap() { couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function (event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted var touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { // Don't let browser turn this into a click event.preventDefault(); this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // Events.fixEvent runs (e.g. event.target) } } }); }; /** * Report user touch activity when touch events occur * User activity is used to determine when controls should show/hide. It's * relatively simple when it comes to mouse events, because any mouse event * should show the controls. So we capture mouse events that bubble up to the * player and report activity when that happens. * With touch events it isn't as easy. We can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). User activity is * checked asynchronously, so what could happen is a tap event on the video * turns the controls off, then the touchend event bubbles up to the player, * which if it reported user activity, would turn the controls right back on. * (We also don't want to completely block touch events from bubbling up) * Also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * Here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. * * @method enableTouchActivity */ Component.prototype.enableTouchActivity = function enableTouchActivity() { // Don't continue if the root player doesn't support reporting user activity if (!this.player() || !this.player().reportUserActivity) { return; } // listener for reporting that the user is active var report = Fn.bind(this.player(), this.player().reportUserActivity); var touchHolding = undefined; this.on('touchstart', function () { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); var touchEnd = function touchEnd(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * Creates timeout and sets up disposal automatically. * * @param {Function} fn The function to run after the timeout. * @param {Number} timeout Number of ms to delay before executing specified function. * @return {Number} Returns the timeout ID * @method setTimeout */ Component.prototype.setTimeout = function setTimeout(fn, timeout) { fn = Fn.bind(this, fn); // window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't. var timeoutId = _globalWindow2['default'].setTimeout(fn, timeout); var disposeFn = function disposeFn() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout and removes the associated dispose listener * * @param {Number} timeoutId The id of the timeout to clear * @return {Number} Returns the timeout ID * @method clearTimeout */ Component.prototype.clearTimeout = function clearTimeout(timeoutId) { _globalWindow2['default'].clearTimeout(timeoutId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates an interval and sets up disposal automatically. * * @param {Function} fn The function to run every N seconds. * @param {Number} interval Number of ms to delay before executing specified function. * @return {Number} Returns the interval ID * @method setInterval */ Component.prototype.setInterval = function setInterval(fn, interval) { fn = Fn.bind(this, fn); var intervalId = _globalWindow2['default'].setInterval(fn, interval); var disposeFn = function disposeFn() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-' + intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval and removes the associated dispose listener * * @param {Number} intervalId The id of the interval to clear * @return {Number} Returns the interval ID * @method clearInterval */ Component.prototype.clearInterval = function clearInterval(intervalId) { _globalWindow2['default'].clearInterval(intervalId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-interval-' + intervalId; this.off('dispose', disposeFn); return intervalId; }; /** * Registers a component * * @param {String} name Name of the component to register * @param {Object} comp The component to register * @static * @method registerComponent */ Component.registerComponent = function registerComponent(name, comp) { if (!Component.components_) { Component.components_ = {}; } Component.components_[name] = comp; return comp; }; /** * Gets a component by name * * @param {String} name Name of the component to get * @return {Component} * @static * @method getComponent */ Component.getComponent = function getComponent(name) { if (Component.components_ && Component.components_[name]) { return Component.components_[name]; } if (_globalWindow2['default'] && _globalWindow2['default'].videojs && _globalWindow2['default'].videojs[name]) { _utilsLogJs2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)'); return _globalWindow2['default'].videojs[name]; } }; /** * Sets up the constructor using the supplied init method * or uses the init of the parent object * * @param {Object} props An object of properties * @static * @deprecated * @method extend */ Component.extend = function extend(props) { props = props || {}; _utilsLogJs2['default'].warn('Component.extend({}) has been deprecated, use videojs.extend(Component, {}) instead'); // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. var subObj = function subObj() { init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = Object.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = Component.extend; // Extend subObj's prototype with functions and other properties from props for (var _name in props) { if (props.hasOwnProperty(_name)) { subObj.prototype[_name] = props[_name]; } } return subObj; }; return Component; })(); Component.registerComponent('Component', Component); exports['default'] = Component; module.exports = exports['default']; },{"./utils/dom.js":132,"./utils/events.js":133,"./utils/fn.js":134,"./utils/guid.js":136,"./utils/log.js":137,"./utils/merge-options.js":138,"./utils/to-title-case.js":141,"global/window":2,"object.assign":45}],68:[function(_dereq_,module,exports){ /** * @file control-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); // Required children var _playToggleJs = _dereq_('./play-toggle.js'); var _playToggleJs2 = _interopRequireDefault(_playToggleJs); var _timeControlsCurrentTimeDisplayJs = _dereq_('./time-controls/current-time-display.js'); var _timeControlsCurrentTimeDisplayJs2 = _interopRequireDefault(_timeControlsCurrentTimeDisplayJs); var _timeControlsDurationDisplayJs = _dereq_('./time-controls/duration-display.js'); var _timeControlsDurationDisplayJs2 = _interopRequireDefault(_timeControlsDurationDisplayJs); var _timeControlsTimeDividerJs = _dereq_('./time-controls/time-divider.js'); var _timeControlsTimeDividerJs2 = _interopRequireDefault(_timeControlsTimeDividerJs); var _timeControlsRemainingTimeDisplayJs = _dereq_('./time-controls/remaining-time-display.js'); var _timeControlsRemainingTimeDisplayJs2 = _interopRequireDefault(_timeControlsRemainingTimeDisplayJs); var _liveDisplayJs = _dereq_('./live-display.js'); var _liveDisplayJs2 = _interopRequireDefault(_liveDisplayJs); var _progressControlProgressControlJs = _dereq_('./progress-control/progress-control.js'); var _progressControlProgressControlJs2 = _interopRequireDefault(_progressControlProgressControlJs); var _fullscreenToggleJs = _dereq_('./fullscreen-toggle.js'); var _fullscreenToggleJs2 = _interopRequireDefault(_fullscreenToggleJs); var _volumeControlVolumeControlJs = _dereq_('./volume-control/volume-control.js'); var _volumeControlVolumeControlJs2 = _interopRequireDefault(_volumeControlVolumeControlJs); var _volumeMenuButtonJs = _dereq_('./volume-menu-button.js'); var _volumeMenuButtonJs2 = _interopRequireDefault(_volumeMenuButtonJs); var _muteToggleJs = _dereq_('./mute-toggle.js'); var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs); var _textTrackControlsChaptersButtonJs = _dereq_('./text-track-controls/chapters-button.js'); var _textTrackControlsChaptersButtonJs2 = _interopRequireDefault(_textTrackControlsChaptersButtonJs); var _textTrackControlsSubtitlesButtonJs = _dereq_('./text-track-controls/subtitles-button.js'); var _textTrackControlsSubtitlesButtonJs2 = _interopRequireDefault(_textTrackControlsSubtitlesButtonJs); var _textTrackControlsCaptionsButtonJs = _dereq_('./text-track-controls/captions-button.js'); var _textTrackControlsCaptionsButtonJs2 = _interopRequireDefault(_textTrackControlsCaptionsButtonJs); var _playbackRateMenuPlaybackRateMenuButtonJs = _dereq_('./playback-rate-menu/playback-rate-menu-button.js'); var _playbackRateMenuPlaybackRateMenuButtonJs2 = _interopRequireDefault(_playbackRateMenuPlaybackRateMenuButtonJs); var _spacerControlsCustomControlSpacerJs = _dereq_('./spacer-controls/custom-control-spacer.js'); var _spacerControlsCustomControlSpacerJs2 = _interopRequireDefault(_spacerControlsCustomControlSpacerJs); /** * Container of main controls * * @extends Component * @class ControlBar */ var ControlBar = (function (_Component) { _inherits(ControlBar, _Component); function ControlBar() { _classCallCheck(this, ControlBar); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ControlBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-control-bar' }, { 'role': 'group' // The control bar is a group, so it can contain menuitems }); }; return ControlBar; })(_componentJs2['default']); ControlBar.prototype.options_ = { loadEvent: 'play', children: ['playToggle', 'volumeMenuButton', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'subtitlesButton', 'captionsButton', 'fullscreenToggle'] }; _componentJs2['default'].registerComponent('ControlBar', ControlBar); exports['default'] = ControlBar; module.exports = exports['default']; },{"../component.js":67,"./fullscreen-toggle.js":69,"./live-display.js":70,"./mute-toggle.js":71,"./play-toggle.js":72,"./playback-rate-menu/playback-rate-menu-button.js":73,"./progress-control/progress-control.js":78,"./spacer-controls/custom-control-spacer.js":80,"./text-track-controls/captions-button.js":83,"./text-track-controls/chapters-button.js":84,"./text-track-controls/subtitles-button.js":87,"./time-controls/current-time-display.js":90,"./time-controls/duration-display.js":91,"./time-controls/remaining-time-display.js":92,"./time-controls/time-divider.js":93,"./volume-control/volume-control.js":95,"./volume-menu-button.js":97}],69:[function(_dereq_,module,exports){ /** * @file fullscreen-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Toggle fullscreen video * * @extends Button * @class FullscreenToggle */ var FullscreenToggle = (function (_Button) { _inherits(FullscreenToggle, _Button); function FullscreenToggle() { _classCallCheck(this, FullscreenToggle); _Button.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handles click for full screen * * @method handleClick */ FullscreenToggle.prototype.handleClick = function handleClick() { if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); this.controlText('Non-Fullscreen'); } else { this.player_.exitFullscreen(); this.controlText('Fullscreen'); } }; return FullscreenToggle; })(_buttonJs2['default']); FullscreenToggle.prototype.controlText_ = 'Fullscreen'; _componentJs2['default'].registerComponent('FullscreenToggle', FullscreenToggle); exports['default'] = FullscreenToggle; module.exports = exports['default']; },{"../button.js":64,"../component.js":67}],70:[function(_dereq_,module,exports){ /** * @file live-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Displays the live indicator * TODO - Future make it click to snap to live * * @extends Component * @class LiveDisplay */ var LiveDisplay = (function (_Component) { _inherits(LiveDisplay, _Component); function LiveDisplay(player, options) { _classCallCheck(this, LiveDisplay); _Component.call(this, player, options); this.updateShowing(); this.on(this.player(), 'durationchange', this.updateShowing); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ LiveDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE') }, { 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; LiveDisplay.prototype.updateShowing = function updateShowing() { if (this.player().duration() === Infinity) { this.show(); } else { this.hide(); } }; return LiveDisplay; })(_component2['default']); _component2['default'].registerComponent('LiveDisplay', LiveDisplay); exports['default'] = LiveDisplay; module.exports = exports['default']; },{"../component":67,"../utils/dom.js":132}],71:[function(_dereq_,module,exports){ /** * @file mute-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _button = _dereq_('../button'); var _button2 = _interopRequireDefault(_button); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * A button component for muting the audio * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MuteToggle */ var MuteToggle = (function (_Button) { _inherits(MuteToggle, _Button); function MuteToggle(player, options) { _classCallCheck(this, MuteToggle); _Button.call(this, player, options); this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech_ && player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { this.update(); // We need to update the button to account for a default muted state. if (player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MuteToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click on mute * * @method handleClick */ MuteToggle.prototype.handleClick = function handleClick() { this.player_.muted(this.player_.muted() ? false : true); }; /** * Update volume * * @method update */ MuteToggle.prototype.update = function update() { var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. var toMute = this.player_.muted() ? 'Unmute' : 'Mute'; if (this.controlText() !== toMute) { this.controlText(toMute); } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { Dom.removeElClass(this.el_, 'vjs-vol-' + i); } Dom.addElClass(this.el_, 'vjs-vol-' + level); }; return MuteToggle; })(_button2['default']); MuteToggle.prototype.controlText_ = 'Mute'; _component2['default'].registerComponent('MuteToggle', MuteToggle); exports['default'] = MuteToggle; module.exports = exports['default']; },{"../button":64,"../component":67,"../utils/dom.js":132}],72:[function(_dereq_,module,exports){ /** * @file play-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Button to toggle between play and pause * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PlayToggle */ var PlayToggle = (function (_Button) { _inherits(PlayToggle, _Button); function PlayToggle(player, options) { _classCallCheck(this, PlayToggle); _Button.call(this, player, options); this.on(player, 'play', this.handlePlay); this.on(player, 'pause', this.handlePause); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlayToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click to toggle between play and pause * * @method handleClick */ PlayToggle.prototype.handleClick = function handleClick() { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; /** * Add the vjs-playing class to the element so it can change appearance * * @method handlePlay */ PlayToggle.prototype.handlePlay = function handlePlay() { this.removeClass('vjs-paused'); this.addClass('vjs-playing'); this.controlText('Pause'); // change the button text to "Pause" }; /** * Add the vjs-paused class to the element so it can change appearance * * @method handlePause */ PlayToggle.prototype.handlePause = function handlePause() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.controlText('Play'); // change the button text to "Play" }; return PlayToggle; })(_buttonJs2['default']); PlayToggle.prototype.controlText_ = 'Play'; _componentJs2['default'].registerComponent('PlayToggle', PlayToggle); exports['default'] = PlayToggle; module.exports = exports['default']; },{"../button.js":64,"../component.js":67}],73:[function(_dereq_,module,exports){ /** * @file playback-rate-menu-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _menuMenuButtonJs = _dereq_('../../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _menuMenuJs = _dereq_('../../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _playbackRateMenuItemJs = _dereq_('./playback-rate-menu-item.js'); var _playbackRateMenuItemJs2 = _interopRequireDefault(_playbackRateMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * The component for controlling the playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class PlaybackRateMenuButton */ var PlaybackRateMenuButton = (function (_MenuButton) { _inherits(PlaybackRateMenuButton, _MenuButton); function PlaybackRateMenuButton(player, options) { _classCallCheck(this, PlaybackRateMenuButton); _MenuButton.call(this, player, options); this.updateVisibility(); this.updateLabel(); this.on(player, 'loadstart', this.updateVisibility); this.on(player, 'ratechange', this.updateLabel); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlaybackRateMenuButton.prototype.createEl = function createEl() { var el = _MenuButton.prototype.createEl.call(this); this.labelEl_ = Dom.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1.0 }); el.appendChild(this.labelEl_); return el; }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this); }; /** * Create the playback rate menu * * @return {Menu} Menu object populated with items * @method createMenu */ PlaybackRateMenuButton.prototype.createMenu = function createMenu() { var menu = new _menuMenuJs2['default'](this.player()); var rates = this.playbackRates(); if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild(new _playbackRateMenuItemJs2['default'](this.player(), { 'rate': rates[i] + 'x' })); } } return menu; }; /** * Updates ARIA accessibility attributes * * @method updateARIAAttributes */ PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; /** * Handle menu item click * * @method handleClick */ PlaybackRateMenuButton.prototype.handleClick = function handleClick() { // select next rate option var currentRate = this.player().playbackRate(); var rates = this.playbackRates(); // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i < rates.length; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; /** * Get possible playback rates * * @return {Array} Possible playback rates * @method playbackRates */ PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() { return this.options_['playbackRates'] || this.options_.playerOptions && this.options_.playerOptions['playbackRates']; }; /** * Get supported playback rates * * @return {Array} Supported playback rates * @method playbackRateSupported */ PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() { return this.player().tech_ && this.player().tech_['featuresPlaybackRate'] && this.playbackRates() && this.playbackRates().length > 0; }; /** * Hide playback rate controls when they're no playback rate options to select * * @method updateVisibility */ PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility() { if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed * * @method updateLabel */ PlaybackRateMenuButton.prototype.updateLabel = function updateLabel() { if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; return PlaybackRateMenuButton; })(_menuMenuButtonJs2['default']); PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate'; _componentJs2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton); exports['default'] = PlaybackRateMenuButton; module.exports = exports['default']; },{"../../component.js":67,"../../menu/menu-button.js":104,"../../menu/menu.js":106,"../../utils/dom.js":132,"./playback-rate-menu-item.js":74}],74:[function(_dereq_,module,exports){ /** * @file playback-rate-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The specific menu item type for selecting a playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class PlaybackRateMenuItem */ var PlaybackRateMenuItem = (function (_MenuItem) { _inherits(PlaybackRateMenuItem, _MenuItem); function PlaybackRateMenuItem(player, options) { _classCallCheck(this, PlaybackRateMenuItem); var label = options['rate']; var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options['label'] = label; options['selected'] = rate === 1; _MenuItem.call(this, player, options); this.label = label; this.rate = rate; this.on(player, 'ratechange', this.update); } /** * Handle click on menu item * * @method handleClick */ PlaybackRateMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player().playbackRate(this.rate); }; /** * Update playback rate with selected rate * * @method update */ PlaybackRateMenuItem.prototype.update = function update() { this.selected(this.player().playbackRate() === this.rate); }; return PlaybackRateMenuItem; })(_menuMenuItemJs2['default']); PlaybackRateMenuItem.prototype.contentElType = 'button'; _componentJs2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem); exports['default'] = PlaybackRateMenuItem; module.exports = exports['default']; },{"../../component.js":67,"../../menu/menu-item.js":105}],75:[function(_dereq_,module,exports){ /** * @file load-progress-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Shows load progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class LoadProgressBar */ var LoadProgressBar = (function (_Component) { _inherits(LoadProgressBar, _Component); function LoadProgressBar(player, options) { _classCallCheck(this, LoadProgressBar); _Component.call(this, player, options); this.on(player, 'progress', this.update); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ LoadProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; /** * Update progress bar * * @method update */ LoadProgressBar.prototype.update = function update() { var buffered = this.player_.buffered(); var duration = this.player_.duration(); var bufferedEnd = this.player_.bufferedEnd(); var children = this.el_.children; // get the percent width of a time compared to the total end var percentify = function percentify(time, end) { var percent = time / end || 0; // no NaN return (percent >= 1 ? 1 : percent) * 100 + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); var part = children[i]; if (!part) { part = this.el_.appendChild(Dom.createEl()); } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (var i = children.length; i > buffered.length; i--) { this.el_.removeChild(children[i - 1]); } }; return LoadProgressBar; })(_componentJs2['default']); _componentJs2['default'].registerComponent('LoadProgressBar', LoadProgressBar); exports['default'] = LoadProgressBar; module.exports = exports['default']; },{"../../component.js":67,"../../utils/dom.js":132}],76:[function(_dereq_,module,exports){ /** * @file mouse-time-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); var _lodashCompatFunctionThrottle = _dereq_('lodash-compat/function/throttle'); var _lodashCompatFunctionThrottle2 = _interopRequireDefault(_lodashCompatFunctionThrottle); /** * The Mouse Time Display component shows the time you will seek to * when hovering over the progress bar * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class MouseTimeDisplay */ var MouseTimeDisplay = (function (_Component) { _inherits(MouseTimeDisplay, _Component); function MouseTimeDisplay(player, options) { var _this = this; _classCallCheck(this, MouseTimeDisplay); _Component.call(this, player, options); this.update(0, 0); player.on('ready', function () { _this.on(player.controlBar.progressControl.el(), 'mousemove', _lodashCompatFunctionThrottle2['default'](Fn.bind(_this, _this.handleMouseMove), 25)); }); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ MouseTimeDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-mouse-display' }); }; MouseTimeDisplay.prototype.handleMouseMove = function handleMouseMove(event) { var duration = this.player_.duration(); var newTime = this.calculateDistance(event) * duration; var position = event.pageX - Dom.findElPosition(this.el().parentNode).left; this.update(newTime, position); }; MouseTimeDisplay.prototype.update = function update(newTime, position) { var time = _utilsFormatTimeJs2['default'](newTime, this.player_.duration()); this.el().style.left = position + 'px'; this.el().setAttribute('data-current-time', time); }; MouseTimeDisplay.prototype.calculateDistance = function calculateDistance(event) { return Dom.getPointerPosition(this.el().parentNode, event).x; }; return MouseTimeDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('MouseTimeDisplay', MouseTimeDisplay); exports['default'] = MouseTimeDisplay; module.exports = exports['default']; },{"../../component.js":67,"../../utils/dom.js":132,"../../utils/fn.js":134,"../../utils/format-time.js":135,"lodash-compat/function/throttle":7}],77:[function(_dereq_,module,exports){ /** * @file play-progress-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Shows play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class PlayProgressBar */ var PlayProgressBar = (function (_Component) { _inherits(PlayProgressBar, _Component); function PlayProgressBar(player, options) { _classCallCheck(this, PlayProgressBar); _Component.call(this, player, options); this.updateDataAttr(); this.on(player, 'timeupdate', this.updateDataAttr); player.ready(Fn.bind(this, this.updateDataAttr)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlayProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress vjs-slider-bar', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; PlayProgressBar.prototype.updateDataAttr = function updateDataAttr() { var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('data-current-time', _utilsFormatTimeJs2['default'](time, this.player_.duration())); }; return PlayProgressBar; })(_componentJs2['default']); _componentJs2['default'].registerComponent('PlayProgressBar', PlayProgressBar); exports['default'] = PlayProgressBar; module.exports = exports['default']; },{"../../component.js":67,"../../utils/fn.js":134,"../../utils/format-time.js":135}],78:[function(_dereq_,module,exports){ /** * @file progress-control.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _seekBarJs = _dereq_('./seek-bar.js'); var _seekBarJs2 = _interopRequireDefault(_seekBarJs); var _mouseTimeDisplayJs = _dereq_('./mouse-time-display.js'); var _mouseTimeDisplayJs2 = _interopRequireDefault(_mouseTimeDisplayJs); /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class ProgressControl */ var ProgressControl = (function (_Component) { _inherits(ProgressControl, _Component); function ProgressControl() { _classCallCheck(this, ProgressControl); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ProgressControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; return ProgressControl; })(_componentJs2['default']); ProgressControl.prototype.options_ = { children: ['seekBar'] }; _componentJs2['default'].registerComponent('ProgressControl', ProgressControl); exports['default'] = ProgressControl; module.exports = exports['default']; },{"../../component.js":67,"./mouse-time-display.js":76,"./seek-bar.js":79}],79:[function(_dereq_,module,exports){ /** * @file seek-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _sliderSliderJs = _dereq_('../../slider/slider.js'); var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _loadProgressBarJs = _dereq_('./load-progress-bar.js'); var _loadProgressBarJs2 = _interopRequireDefault(_loadProgressBarJs); var _playProgressBarJs = _dereq_('./play-progress-bar.js'); var _playProgressBarJs2 = _interopRequireDefault(_playProgressBarJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * Seek Bar and holder for the progress bars * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class SeekBar */ var SeekBar = (function (_Slider) { _inherits(SeekBar, _Slider); function SeekBar(player, options) { _classCallCheck(this, SeekBar); _Slider.call(this, player, options); this.on(player, 'timeupdate', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ SeekBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder' }, { 'aria-label': 'video progress bar' }); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ SeekBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('aria-valuenow', (this.getPercent() * 100).toFixed(2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext', _utilsFormatTimeJs2['default'](time, this.player_.duration())); // human readable value of progress bar (time complete) }; /** * Get percentage of video played * * @return {Number} Percentage played * @method getPercent */ SeekBar.prototype.getPercent = function getPercent() { var percent = this.player_.currentTime() / this.player_.duration(); return percent >= 1 ? 1 : percent; }; /** * Handle mouse down on seek bar * * @method handleMouseDown */ SeekBar.prototype.handleMouseDown = function handleMouseDown(event) { _Slider.prototype.handleMouseDown.call(this, event); this.player_.scrubbing(true); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; /** * Handle mouse move on seek bar * * @method handleMouseMove */ SeekBar.prototype.handleMouseMove = function handleMouseMove(event) { var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime === this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; /** * Handle mouse up on seek bar * * @method handleMouseUp */ SeekBar.prototype.handleMouseUp = function handleMouseUp(event) { _Slider.prototype.handleMouseUp.call(this, event); this.player_.scrubbing(false); if (this.videoWasPlaying) { this.player_.play(); } }; /** * Move more quickly fast forward for keyboard-only users * * @method stepForward */ SeekBar.prototype.stepForward = function stepForward() { this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; /** * Move more quickly rewind for keyboard-only users * * @method stepBack */ SeekBar.prototype.stepBack = function stepBack() { this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; return SeekBar; })(_sliderSliderJs2['default']); SeekBar.prototype.options_ = { children: ['loadProgressBar', 'mouseTimeDisplay', 'playProgressBar'], 'barName': 'playProgressBar' }; SeekBar.prototype.playerEvent = 'timeupdate'; _componentJs2['default'].registerComponent('SeekBar', SeekBar); exports['default'] = SeekBar; module.exports = exports['default']; },{"../../component.js":67,"../../slider/slider.js":114,"../../utils/fn.js":134,"../../utils/format-time.js":135,"./load-progress-bar.js":75,"./play-progress-bar.js":77,"object.assign":45}],80:[function(_dereq_,module,exports){ /** * @file custom-control-spacer.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _spacerJs = _dereq_('./spacer.js'); var _spacerJs2 = _interopRequireDefault(_spacerJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Spacer specifically meant to be used as an insertion point for new plugins, etc. * * @extends Spacer * @class CustomControlSpacer */ var CustomControlSpacer = (function (_Spacer) { _inherits(CustomControlSpacer, _Spacer); function CustomControlSpacer() { _classCallCheck(this, CustomControlSpacer); _Spacer.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ CustomControlSpacer.prototype.createEl = function createEl() { var el = _Spacer.prototype.createEl.call(this, { className: this.buildCSSClass() }); // No-flex/table-cell mode requires there be some content // in the cell to fill the remaining space of the table. el.innerHTML = '&nbsp;'; return el; }; return CustomControlSpacer; })(_spacerJs2['default']); _componentJs2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer); exports['default'] = CustomControlSpacer; module.exports = exports['default']; },{"../../component.js":67,"./spacer.js":81}],81:[function(_dereq_,module,exports){ /** * @file spacer.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Just an empty spacer element that can be used as an append point for plugins, etc. * Also can be used to create space between elements when necessary. * * @extends Component * @class Spacer */ var Spacer = (function (_Component) { _inherits(Spacer, _Component); function Spacer() { _classCallCheck(this, Spacer); _Component.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Spacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Spacer.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; return Spacer; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Spacer', Spacer); exports['default'] = Spacer; module.exports = exports['default']; },{"../../component.js":67}],82:[function(_dereq_,module,exports){ /** * @file caption-settings-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The menu item for caption track settings menu * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class CaptionSettingsMenuItem */ var CaptionSettingsMenuItem = (function (_TextTrackMenuItem) { _inherits(CaptionSettingsMenuItem, _TextTrackMenuItem); function CaptionSettingsMenuItem(player, options) { _classCallCheck(this, CaptionSettingsMenuItem); options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' settings', 'selectable': false, 'default': false, mode: 'disabled' }; // CaptionSettingsMenuItem has no concept of 'selected' options['selectable'] = false; _TextTrackMenuItem.call(this, player, options); this.addClass('vjs-texttrack-settings'); this.controlText(', opens ' + options['kind'] + ' settings dialog'); } /** * Handle click on menu item * * @method handleClick */ CaptionSettingsMenuItem.prototype.handleClick = function handleClick() { this.player().getChild('textTrackSettings').show(); this.player().getChild('textTrackSettings').el_.focus(); }; return CaptionSettingsMenuItem; })(_textTrackMenuItemJs2['default']); _componentJs2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem); exports['default'] = CaptionSettingsMenuItem; module.exports = exports['default']; },{"../../component.js":67,"./text-track-menu-item.js":89}],83:[function(_dereq_,module,exports){ /** * @file captions-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _captionSettingsMenuItemJs = _dereq_('./caption-settings-menu-item.js'); var _captionSettingsMenuItemJs2 = _interopRequireDefault(_captionSettingsMenuItemJs); /** * The button component for toggling and selecting captions * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class CaptionsButton */ var CaptionsButton = (function (_TextTrackButton) { _inherits(CaptionsButton, _TextTrackButton); function CaptionsButton(player, options, ready) { _classCallCheck(this, CaptionsButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Captions Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CaptionsButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Update caption menu items * * @method update */ CaptionsButton.prototype.update = function update() { var threshold = 2; _TextTrackButton.prototype.update.call(this); // if native, then threshold is 1 because no settings button if (this.player().tech_ && this.player().tech_['featuresNativeTextTracks']) { threshold = 1; } if (this.items && this.items.length > threshold) { this.show(); } else { this.hide(); } }; /** * Create caption menu items * * @return {Array} Array of menu items * @method createItems */ CaptionsButton.prototype.createItems = function createItems() { var items = []; if (!(this.player().tech_ && this.player().tech_['featuresNativeTextTracks'])) { items.push(new _captionSettingsMenuItemJs2['default'](this.player_, { 'kind': this.kind_ })); } return _TextTrackButton.prototype.createItems.call(this, items); }; return CaptionsButton; })(_textTrackButtonJs2['default']); CaptionsButton.prototype.kind_ = 'captions'; CaptionsButton.prototype.controlText_ = 'Captions'; _componentJs2['default'].registerComponent('CaptionsButton', CaptionsButton); exports['default'] = CaptionsButton; module.exports = exports['default']; },{"../../component.js":67,"./caption-settings-menu-item.js":82,"./text-track-button.js":88}],84:[function(_dereq_,module,exports){ /** * @file chapters-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _chaptersTrackMenuItemJs = _dereq_('./chapters-track-menu-item.js'); var _chaptersTrackMenuItemJs2 = _interopRequireDefault(_chaptersTrackMenuItemJs); var _menuMenuJs = _dereq_('../../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsToTitleCaseJs = _dereq_('../../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * The button component for toggling and selecting chapters * Chapters act much differently than other text tracks * Cues are navigation vs. other tracks of alternative languages * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class ChaptersButton */ var ChaptersButton = (function (_TextTrackButton) { _inherits(ChaptersButton, _TextTrackButton); function ChaptersButton(player, options, ready) { _classCallCheck(this, ChaptersButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Chapters Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ ChaptersButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Create a menu item for each text track * * @return {Array} Array of menu items * @method createItems */ ChaptersButton.prototype.createItems = function createItems() { var items = []; var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['kind'] === this.kind_) { items.push(new _textTrackMenuItemJs2['default'](this.player_, { 'track': track })); } } return items; }; /** * Create menu from chapter buttons * * @return {Menu} Menu of chapter buttons * @method createMenu */ ChaptersButton.prototype.createMenu = function createMenu() { var _this = this; var tracks = this.player_.textTracks() || []; var chaptersTrack = undefined; var items = this.items = []; for (var i = 0, _length = tracks.length; i < _length; i++) { var track = tracks[i]; if (track['kind'] === this.kind_) { chaptersTrack = track; break; } } var menu = this.menu; if (menu === undefined) { menu = new _menuMenuJs2['default'](this.player_); var title = Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _utilsToTitleCaseJs2['default'](this.kind_), tabIndex: -1 }); menu.children_.unshift(title); Dom.insertElFirst(title, menu.contentEl()); } if (chaptersTrack && chaptersTrack.cues == null) { chaptersTrack['mode'] = 'hidden'; var remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(chaptersTrack); if (remoteTextTrackEl) { remoteTextTrackEl.addEventListener('load', function (event) { return _this.update(); }); } } if (chaptersTrack && chaptersTrack.cues && chaptersTrack.cues.length > 0) { var cues = chaptersTrack['cues'], cue = undefined; for (var i = 0, l = cues.length; i < l; i++) { cue = cues[i]; var mi = new _chaptersTrackMenuItemJs2['default'](this.player_, { 'track': chaptersTrack, 'cue': cue }); items.push(mi); menu.addChild(mi); } this.addChild(menu); } if (this.items.length > 0) { this.show(); } return menu; }; return ChaptersButton; })(_textTrackButtonJs2['default']); ChaptersButton.prototype.kind_ = 'chapters'; ChaptersButton.prototype.controlText_ = 'Chapters'; _componentJs2['default'].registerComponent('ChaptersButton', ChaptersButton); exports['default'] = ChaptersButton; module.exports = exports['default']; },{"../../component.js":67,"../../menu/menu.js":106,"../../utils/dom.js":132,"../../utils/fn.js":134,"../../utils/to-title-case.js":141,"./chapters-track-menu-item.js":85,"./text-track-button.js":88,"./text-track-menu-item.js":89,"global/window":2}],85:[function(_dereq_,module,exports){ /** * @file chapters-track-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); /** * The chapter track menu item * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class ChaptersTrackMenuItem */ var ChaptersTrackMenuItem = (function (_MenuItem) { _inherits(ChaptersTrackMenuItem, _MenuItem); function ChaptersTrackMenuItem(player, options) { _classCallCheck(this, ChaptersTrackMenuItem); var track = options['track']; var cue = options['cue']; var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options['label'] = cue.text; options['selected'] = cue['startTime'] <= currentTime && currentTime < cue['endTime']; _MenuItem.call(this, player, options); this.track = track; this.cue = cue; track.addEventListener('cuechange', Fn.bind(this, this.update)); } /** * Handle click on menu item * * @method handleClick */ ChaptersTrackMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; /** * Update chapter menu item * * @method update */ ChaptersTrackMenuItem.prototype.update = function update() { var cue = this.cue; var currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue['startTime'] <= currentTime && currentTime < cue['endTime']); }; return ChaptersTrackMenuItem; })(_menuMenuItemJs2['default']); _componentJs2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem); exports['default'] = ChaptersTrackMenuItem; module.exports = exports['default']; },{"../../component.js":67,"../../menu/menu-item.js":105,"../../utils/fn.js":134}],86:[function(_dereq_,module,exports){ /** * @file off-text-track-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * A special menu item for turning of a specific type of text track * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class OffTextTrackMenuItem */ var OffTextTrackMenuItem = (function (_TextTrackMenuItem) { _inherits(OffTextTrackMenuItem, _TextTrackMenuItem); function OffTextTrackMenuItem(player, options) { _classCallCheck(this, OffTextTrackMenuItem); // Create pseudo track info // Requires options['kind'] options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' off', 'default': false, 'mode': 'disabled' }; // MenuItem is selectable options['selectable'] = true; _TextTrackMenuItem.call(this, player, options); this.selected(true); } /** * Handle text track change * * @param {Object} event Event object * @method handleTracksChange */ OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var selected = true; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track['kind'] === this.track['kind'] && track['mode'] === 'showing') { selected = false; break; } } this.selected(selected); }; return OffTextTrackMenuItem; })(_textTrackMenuItemJs2['default']); _componentJs2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem); exports['default'] = OffTextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":67,"./text-track-menu-item.js":89}],87:[function(_dereq_,module,exports){ /** * @file subtitles-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The button component for toggling and selecting subtitles * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class SubtitlesButton */ var SubtitlesButton = (function (_TextTrackButton) { _inherits(SubtitlesButton, _TextTrackButton); function SubtitlesButton(player, options, ready) { _classCallCheck(this, SubtitlesButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Subtitles Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; return SubtitlesButton; })(_textTrackButtonJs2['default']); SubtitlesButton.prototype.kind_ = 'subtitles'; SubtitlesButton.prototype.controlText_ = 'Subtitles'; _componentJs2['default'].registerComponent('SubtitlesButton', SubtitlesButton); exports['default'] = SubtitlesButton; module.exports = exports['default']; },{"../../component.js":67,"./text-track-button.js":88}],88:[function(_dereq_,module,exports){ /** * @file text-track-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _menuMenuButtonJs = _dereq_('../../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _offTextTrackMenuItemJs = _dereq_('./off-text-track-menu-item.js'); var _offTextTrackMenuItemJs2 = _interopRequireDefault(_offTextTrackMenuItemJs); /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class TextTrackButton */ var TextTrackButton = (function (_MenuButton) { _inherits(TextTrackButton, _MenuButton); function TextTrackButton(player, options) { _classCallCheck(this, TextTrackButton); _MenuButton.call(this, player, options); var tracks = this.player_.textTracks(); if (this.items.length <= 1) { this.hide(); } if (!tracks) { return; } var updateHandler = Fn.bind(this, this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); this.player_.on('dispose', function () { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); } // Create a menu item for each text track TextTrackButton.prototype.createItems = function createItems() { var items = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; // Add an OFF menu item to turn all tracks off items.push(new _offTextTrackMenuItemJs2['default'](this.player_, { 'kind': this.kind_ })); var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // only add tracks that are of the appropriate kind and have a label if (track['kind'] === this.kind_) { items.push(new _textTrackMenuItemJs2['default'](this.player_, { // MenuItem is selectable 'selectable': true, 'track': track })); } } return items; }; return TextTrackButton; })(_menuMenuButtonJs2['default']); _componentJs2['default'].registerComponent('TextTrackButton', TextTrackButton); exports['default'] = TextTrackButton; module.exports = exports['default']; },{"../../component.js":67,"../../menu/menu-button.js":104,"../../utils/fn.js":134,"./off-text-track-menu-item.js":86,"./text-track-menu-item.js":89}],89:[function(_dereq_,module,exports){ /** * @file text-track-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * The specific menu item type for selecting a language within a text track kind * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class TextTrackMenuItem */ var TextTrackMenuItem = (function (_MenuItem) { _inherits(TextTrackMenuItem, _MenuItem); function TextTrackMenuItem(player, options) { var _this = this; _classCallCheck(this, TextTrackMenuItem); var track = options['track']; var tracks = player.textTracks(); // Modify options for parent MenuItem class's init. options['label'] = track['label'] || track['language'] || 'Unknown'; options['selected'] = track['default'] || track['mode'] === 'showing'; _MenuItem.call(this, player, options); this.track = track; if (tracks) { (function () { var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); })(); } // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks && tracks.onchange === undefined) { (function () { var event = undefined; _this.on(['tap', 'click'], function () { if (typeof _globalWindow2['default'].Event !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new _globalWindow2['default'].Event('change'); } catch (err) {} } if (!event) { event = _globalDocument2['default'].createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); })(); } } /** * Handle click on text track * * @method handleClick */ TextTrackMenuItem.prototype.handleClick = function handleClick(event) { var kind = this.track['kind']; var tracks = this.player_.textTracks(); _MenuItem.prototype.handleClick.call(this, event); if (!tracks) return; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['kind'] !== kind) { continue; } if (track === this.track) { track['mode'] = 'showing'; } else { track['mode'] = 'disabled'; } } }; /** * Handle text track change * * @method handleTracksChange */ TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { this.selected(this.track['mode'] === 'showing'); }; return TextTrackMenuItem; })(_menuMenuItemJs2['default']); _componentJs2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem); exports['default'] = TextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":67,"../../menu/menu-item.js":105,"../../utils/fn.js":134,"global/document":1,"global/window":2}],90:[function(_dereq_,module,exports){ /** * @file current-time-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the current time * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class CurrentTimeDisplay */ var CurrentTimeDisplay = (function (_Component) { _inherits(CurrentTimeDisplay, _Component); function CurrentTimeDisplay(player, options) { _classCallCheck(this, CurrentTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ CurrentTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-current-time-display', // label the current time for screen reader users innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update current time display * * @method updateContent */ CurrentTimeDisplay.prototype.updateContent = function updateContent() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); var localizedText = this.localize('Current Time'); var formattedTime = _utilsFormatTimeJs2['default'](time, this.player_.duration()); if (formattedTime !== this.formattedTime_) { this.formattedTime_ = formattedTime; this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; } }; return CurrentTimeDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay); exports['default'] = CurrentTimeDisplay; module.exports = exports['default']; },{"../../component.js":67,"../../utils/dom.js":132,"../../utils/format-time.js":135}],91:[function(_dereq_,module,exports){ /** * @file duration-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the duration * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class DurationDisplay */ var DurationDisplay = (function (_Component) { _inherits(DurationDisplay, _Component); function DurationDisplay(player, options) { _classCallCheck(this, DurationDisplay); _Component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updateContent); this.on(player, 'loadedmetadata', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ DurationDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-duration-display', // label the duration time for screen reader users innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update duration time display * * @method updateContent */ DurationDisplay.prototype.updateContent = function updateContent() { var duration = this.player_.duration(); if (duration && this.duration_ !== duration) { this.duration_ = duration; var localizedText = this.localize('Duration Time'); var formattedTime = _utilsFormatTimeJs2['default'](duration); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; // label the duration time for screen reader users } }; return DurationDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('DurationDisplay', DurationDisplay); exports['default'] = DurationDisplay; module.exports = exports['default']; },{"../../component.js":67,"../../utils/dom.js":132,"../../utils/format-time.js":135}],92:[function(_dereq_,module,exports){ /** * @file remaining-time-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the time left in the video * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class RemainingTimeDisplay */ var RemainingTimeDisplay = (function (_Component) { _inherits(RemainingTimeDisplay, _Component); function RemainingTimeDisplay(player, options) { _classCallCheck(this, RemainingTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ RemainingTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-remaining-time-display', // label the remaining time for screen reader users innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update remaining time display * * @method updateContent */ RemainingTimeDisplay.prototype.updateContent = function updateContent() { if (this.player_.duration()) { var localizedText = this.localize('Remaining Time'); var formattedTime = _utilsFormatTimeJs2['default'](this.player_.remainingTime()); if (formattedTime !== this.formattedTime_) { this.formattedTime_ = formattedTime; this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime; } } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing()) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; return RemainingTimeDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay); exports['default'] = RemainingTimeDisplay; module.exports = exports['default']; },{"../../component.js":67,"../../utils/dom.js":132,"../../utils/format-time.js":135}],93:[function(_dereq_,module,exports){ /** * @file time-divider.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The separator between the current time and duration. * Can be hidden if it's not needed in the design. * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class TimeDivider */ var TimeDivider = (function (_Component) { _inherits(TimeDivider, _Component); function TimeDivider() { _classCallCheck(this, TimeDivider); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ TimeDivider.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-control vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; return TimeDivider; })(_componentJs2['default']); _componentJs2['default'].registerComponent('TimeDivider', TimeDivider); exports['default'] = TimeDivider; module.exports = exports['default']; },{"../../component.js":67}],94:[function(_dereq_,module,exports){ /** * @file volume-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _sliderSliderJs = _dereq_('../../slider/slider.js'); var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); // Required children var _volumeLevelJs = _dereq_('./volume-level.js'); var _volumeLevelJs2 = _interopRequireDefault(_volumeLevelJs); /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class VolumeBar */ var VolumeBar = (function (_Slider) { _inherits(VolumeBar, _Slider); function VolumeBar(player, options) { _classCallCheck(this, VolumeBar); _Slider.call(this, player, options); this.on(player, 'volumechange', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar vjs-slider-bar' }, { 'aria-label': 'volume level' }); }; /** * Handle mouse move on volume bar * * @method handleMouseMove */ VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) { this.checkMuted(); this.player_.volume(this.calculateDistance(event)); }; VolumeBar.prototype.checkMuted = function checkMuted() { if (this.player_.muted()) { this.player_.muted(false); } }; /** * Get percent of volume level * * @retun {Number} Volume level percent * @method getPercent */ VolumeBar.prototype.getPercent = function getPercent() { if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; /** * Increase volume level for keyboard users * * @method stepForward */ VolumeBar.prototype.stepForward = function stepForward() { this.checkMuted(); this.player_.volume(this.player_.volume() + 0.1); }; /** * Decrease volume level for keyboard users * * @method stepBack */ VolumeBar.prototype.stepBack = function stepBack() { this.checkMuted(); this.player_.volume(this.player_.volume() - 0.1); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current value of volume bar as a percentage var volume = (this.player_.volume() * 100).toFixed(2); this.el_.setAttribute('aria-valuenow', volume); this.el_.setAttribute('aria-valuetext', volume + '%'); }; return VolumeBar; })(_sliderSliderJs2['default']); VolumeBar.prototype.options_ = { children: ['volumeLevel'], 'barName': 'volumeLevel' }; VolumeBar.prototype.playerEvent = 'volumechange'; _componentJs2['default'].registerComponent('VolumeBar', VolumeBar); exports['default'] = VolumeBar; module.exports = exports['default']; },{"../../component.js":67,"../../slider/slider.js":114,"../../utils/fn.js":134,"./volume-level.js":96}],95:[function(_dereq_,module,exports){ /** * @file volume-control.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); // Required children var _volumeBarJs = _dereq_('./volume-bar.js'); var _volumeBarJs2 = _interopRequireDefault(_volumeBarJs); /** * The component for controlling the volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeControl */ var VolumeControl = (function (_Component) { _inherits(VolumeControl, _Component); function VolumeControl(player, options) { _classCallCheck(this, VolumeControl); _Component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech_ && player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; return VolumeControl; })(_componentJs2['default']); VolumeControl.prototype.options_ = { children: ['volumeBar'] }; _componentJs2['default'].registerComponent('VolumeControl', VolumeControl); exports['default'] = VolumeControl; module.exports = exports['default']; },{"../../component.js":67,"./volume-bar.js":94}],96:[function(_dereq_,module,exports){ /** * @file volume-level.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Shows volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeLevel */ var VolumeLevel = (function (_Component) { _inherits(VolumeLevel, _Component); function VolumeLevel() { _classCallCheck(this, VolumeLevel); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeLevel.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; return VolumeLevel; })(_componentJs2['default']); _componentJs2['default'].registerComponent('VolumeLevel', VolumeLevel); exports['default'] = VolumeLevel; module.exports = exports['default']; },{"../../component.js":67}],97:[function(_dereq_,module,exports){ /** * @file volume-menu-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _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 _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _popupPopupJs = _dereq_('../popup/popup.js'); var _popupPopupJs2 = _interopRequireDefault(_popupPopupJs); var _popupPopupButtonJs = _dereq_('../popup/popup-button.js'); var _popupPopupButtonJs2 = _interopRequireDefault(_popupPopupButtonJs); var _muteToggleJs = _dereq_('./mute-toggle.js'); var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs); var _volumeControlVolumeBarJs = _dereq_('./volume-control/volume-bar.js'); var _volumeControlVolumeBarJs2 = _interopRequireDefault(_volumeControlVolumeBarJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Button for volume popup * * @param {Player|Object} player * @param {Object=} options * @extends PopupButton * @class VolumeMenuButton */ var VolumeMenuButton = (function (_PopupButton) { _inherits(VolumeMenuButton, _PopupButton); function VolumeMenuButton(player) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, VolumeMenuButton); // Default to inline if (options.inline === undefined) { options.inline = true; } // If the vertical option isn't passed at all, default to true. if (options.vertical === undefined) { // If an inline volumeMenuButton is used, we should default to using // a horizontal slider for obvious reasons. if (options.inline) { options.vertical = false; } else { options.vertical = true; } } // The vertical option needs to be set on the volumeBar as well, // since that will need to be passed along to the VolumeBar constructor options.volumeBar = options.volumeBar || {}; options.volumeBar.vertical = !!options.vertical; _PopupButton.call(this, player, options); // Same listeners as MuteToggle this.on(player, 'volumechange', this.volumeUpdate); this.on(player, 'loadstart', this.volumeUpdate); // hide mute toggle if the current tech doesn't support volume control function updateVisibility() { if (player.tech_ && player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } } updateVisibility.call(this); this.on(player, 'loadstart', updateVisibility); this.on(this.volumeBar, ['slideractive', 'focus'], function () { this.addClass('vjs-slider-active'); }); this.on(this.volumeBar, ['sliderinactive', 'blur'], function () { this.removeClass('vjs-slider-active'); }); this.on(this.volumeBar, ['focus'], function () { this.addClass('vjs-lock-showing'); }); this.on(this.volumeBar, ['blur'], function () { this.removeClass('vjs-lock-showing'); }); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ VolumeMenuButton.prototype.buildCSSClass = function buildCSSClass() { var orientationClass = ''; if (!!this.options_.vertical) { orientationClass = 'vjs-volume-menu-button-vertical'; } else { orientationClass = 'vjs-volume-menu-button-horizontal'; } return 'vjs-volume-menu-button ' + _PopupButton.prototype.buildCSSClass.call(this) + ' ' + orientationClass; }; /** * Allow sub components to stack CSS class names * * @return {Popup} The volume popup button * @method createPopup */ VolumeMenuButton.prototype.createPopup = function createPopup() { var popup = new _popupPopupJs2['default'](this.player_, { contentElType: 'div' }); var vb = new _volumeControlVolumeBarJs2['default'](this.player_, this.options_.volumeBar); popup.addChild(vb); this.volumeBar = vb; this.attachVolumeBarEvents(); return popup; }; /** * Handle click on volume popup and calls super * * @method handleClick */ VolumeMenuButton.prototype.handleClick = function handleClick() { _muteToggleJs2['default'].prototype.handleClick.call(this); _PopupButton.prototype.handleClick.call(this); }; VolumeMenuButton.prototype.attachVolumeBarEvents = function attachVolumeBarEvents() { this.on(['mousedown', 'touchdown'], this.handleMouseDown); }; VolumeMenuButton.prototype.handleMouseDown = function handleMouseDown(event) { this.on(['mousemove', 'touchmove'], Fn.bind(this.volumeBar, this.volumeBar.handleMouseMove)); this.on(_globalDocument2['default'], ['mouseup', 'touchend'], this.handleMouseUp); }; VolumeMenuButton.prototype.handleMouseUp = function handleMouseUp(event) { this.off(['mousemove', 'touchmove'], Fn.bind(this.volumeBar, this.volumeBar.handleMouseMove)); }; return VolumeMenuButton; })(_popupPopupButtonJs2['default']); VolumeMenuButton.prototype.volumeUpdate = _muteToggleJs2['default'].prototype.update; VolumeMenuButton.prototype.controlText_ = 'Mute'; _componentJs2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton); exports['default'] = VolumeMenuButton; module.exports = exports['default']; },{"../component.js":67,"../popup/popup-button.js":110,"../popup/popup.js":111,"../utils/fn.js":134,"./mute-toggle.js":71,"./volume-control/volume-bar.js":94,"global/document":1}],98:[function(_dereq_,module,exports){ /** * @file error-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _modalDialog = _dereq_('./modal-dialog'); var _modalDialog2 = _interopRequireDefault(_modalDialog); var _utilsDom = _dereq_('./utils/dom'); var Dom = _interopRequireWildcard(_utilsDom); var _utilsMergeOptions = _dereq_('./utils/merge-options'); var _utilsMergeOptions2 = _interopRequireDefault(_utilsMergeOptions); /** * Display that an error has occurred making the video unplayable. * * @extends ModalDialog * @class ErrorDisplay */ var ErrorDisplay = (function (_ModalDialog) { _inherits(ErrorDisplay, _ModalDialog); /** * Constructor for error display modal. * * @param {Player} player * @param {Object} [options] */ function ErrorDisplay(player, options) { _classCallCheck(this, ErrorDisplay); _ModalDialog.call(this, player, options); this.on(player, 'error', this.open); } /** * Include the old class for backward-compatibility. * * This can be removed in 6.0. * * @method buildCSSClass * @deprecated * @return {String} */ ErrorDisplay.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-error-display ' + _ModalDialog.prototype.buildCSSClass.call(this); }; /** * Generates the modal content based on the player error. * * @return {String|Null} */ ErrorDisplay.prototype.content = function content() { var error = this.player().error(); return error ? this.localize(error.message) : ''; }; return ErrorDisplay; })(_modalDialog2['default']); ErrorDisplay.prototype.options_ = _utilsMergeOptions2['default'](_modalDialog2['default'].prototype.options_, { fillAlways: true, temporary: false, uncloseable: true }); _component2['default'].registerComponent('ErrorDisplay', ErrorDisplay); exports['default'] = ErrorDisplay; module.exports = exports['default']; },{"./component":67,"./modal-dialog":107,"./utils/dom":132,"./utils/merge-options":138}],99:[function(_dereq_,module,exports){ /** * @file event-target.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var EventTarget = function EventTarget() {}; EventTarget.prototype.allowedEvents_ = {}; EventTarget.prototype.on = function (type, fn) { // Remove the addEventListener alias before calling Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = Function.prototype; Events.on(this, type, fn); this.addEventListener = ael; }; EventTarget.prototype.addEventListener = EventTarget.prototype.on; EventTarget.prototype.off = function (type, fn) { Events.off(this, type, fn); }; EventTarget.prototype.removeEventListener = EventTarget.prototype.off; EventTarget.prototype.one = function (type, fn) { Events.one(this, type, fn); }; EventTarget.prototype.trigger = function (event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = Events.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } Events.trigger(this, event); }; // The standard DOM EventTarget.dispatchEvent() is aliased to trigger() EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger; exports['default'] = EventTarget; module.exports = exports['default']; },{"./utils/events.js":133}],100:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsLog = _dereq_('./utils/log'); var _utilsLog2 = _interopRequireDefault(_utilsLog); /* * @file extend.js * * A combination of node inherits and babel's inherits (after transpile). * Both work the same but node adds `super_` to the subClass * and Bable adds the superClass as __proto__. Both seem useful. */ var _inherits = function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) { // node subClass.super_ = superClass; } }; /* * Function for subclassing using the same inheritance that * videojs uses internally * ```js * var Button = videojs.getComponent('Button'); * ``` * ```js * var MyButton = videojs.extend(Button, { * constructor: function(player, options) { * Button.call(this, player, options); * }, * onClick: function() { * // doSomething * } * }); * ``` */ var extendFn = function extendFn(superClass) { var subClassMethods = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var subClass = function subClass() { superClass.apply(this, arguments); }; var methods = {}; if (typeof subClassMethods === 'object') { if (typeof subClassMethods.init === 'function') { _utilsLog2['default'].warn('Constructor logic via init() is deprecated; please use constructor() instead.'); subClassMethods.constructor = subClassMethods.init; } if (subClassMethods.constructor !== Object.prototype.constructor) { subClass = subClassMethods.constructor; } methods = subClassMethods; } else if (typeof subClassMethods === 'function') { subClass = subClassMethods; } _inherits(subClass, superClass); // Extend subObj's prototype with functions and other properties from props for (var name in methods) { if (methods.hasOwnProperty(name)) { subClass.prototype[name] = methods[name]; } } return subClass; }; exports['default'] = extendFn; module.exports = exports['default']; },{"./utils/log":137}],101:[function(_dereq_,module,exports){ /** * @file fullscreen-api.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /* * Store the browser-specific methods for the fullscreen API * @type {Object|undefined} * @private */ var FullscreenApi = {}; // browser API methods // map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js var apiMap = [ // Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html ['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'], // WebKit ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Old WebKit (Safari 5.1) ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Mozilla ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], // Microsoft ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']]; var specApi = apiMap[0]; var browserApi = undefined; // determine the supported set of functions for (var i = 0; i < apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in _globalDocument2['default']) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names if (browserApi) { for (var i = 0; i < browserApi.length; i++) { FullscreenApi[specApi[i]] = browserApi[i]; } } exports['default'] = FullscreenApi; module.exports = exports['default']; },{"global/document":1}],102:[function(_dereq_,module,exports){ /** * @file loading-spinner.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * * @extends Component * @class LoadingSpinner */ var LoadingSpinner = (function (_Component) { _inherits(LoadingSpinner, _Component); function LoadingSpinner() { _classCallCheck(this, LoadingSpinner); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @method createEl */ LoadingSpinner.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; return LoadingSpinner; })(_component2['default']); _component2['default'].registerComponent('LoadingSpinner', LoadingSpinner); exports['default'] = LoadingSpinner; module.exports = exports['default']; },{"./component":67}],103:[function(_dereq_,module,exports){ /** * @file media-error.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /* * Custom MediaError to mimic the HTML5 MediaError * * @param {Number} code The media error code */ var MediaError = function MediaError(code) { if (typeof code === 'number') { this.code = code; } else if (typeof code === 'string') { // default code is zero, so this is a custom error this.message = code; } else if (typeof code === 'object') { // object _objectAssign2['default'](this, code); } if (!this.message) { this.message = MediaError.defaultMessages[this.code] || ''; } }; /* * The error code that refers two one of the defined * MediaError types * * @type {Number} */ MediaError.prototype.code = 0; /* * An optional message to be shown with the error. * Message is not part of the HTML5 video spec * but allows for more informative custom errors. * * @type {String} */ MediaError.prototype.message = ''; /* * An optional status code that can be set by plugins * to allow even more detail about the error. * For example the HLS plugin might provide the specific * HTTP status code that was returned when the error * occurred, then allowing a custom error overlay * to display more information. * * @type {Array} */ MediaError.prototype.status = null; MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', // = 0 'MEDIA_ERR_ABORTED', // = 1 'MEDIA_ERR_NETWORK', // = 2 'MEDIA_ERR_DECODE', // = 3 'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4 'MEDIA_ERR_ENCRYPTED' // = 5 ]; MediaError.defaultMessages = { 1: 'You aborted the media playback', 2: 'A network error caused the media download to fail part-way.', 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.', 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The media is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) { MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance MediaError.prototype[MediaError.errorTypes[errNum]] = errNum; } exports['default'] = MediaError; module.exports = exports['default']; },{"object.assign":45}],104:[function(_dereq_,module,exports){ /** * @file menu-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _clickableComponentJs = _dereq_('../clickable-component.js'); var _clickableComponentJs2 = _interopRequireDefault(_clickableComponentJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _menuJs = _dereq_('./menu.js'); var _menuJs2 = _interopRequireDefault(_menuJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); /** * A button class with a popup menu * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuButton */ var MenuButton = (function (_ClickableComponent) { _inherits(MenuButton, _ClickableComponent); function MenuButton(player) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, MenuButton); _ClickableComponent.call(this, player, options); this.update(); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'menuitem'); this.on('keydown', this.handleSubmenuKeyPress); } /** * Update menu * * @method update */ MenuButton.prototype.update = function update() { var menu = this.createMenu(); if (this.menu) { this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); /** * Track the state of the menu button * * @type {Boolean} * @private */ this.buttonPressed_ = false; this.el_.setAttribute('aria-expanded', false); if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Create menu * * @return {Menu} The constructed menu * @method createMenu */ MenuButton.prototype.createMenu = function createMenu() { var menu = new _menuJs2['default'](this.player_); // Add a title list item to the top if (this.options_.title) { var title = Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _utilsToTitleCaseJs2['default'](this.options_.title), tabIndex: -1 }); menu.children_.unshift(title); Dom.insertElFirst(title, menu.contentEl()); } this.items = this['createItems'](); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. * * @method createItems */ MenuButton.prototype.createItems = function createItems() {}; /** * Create the component's DOM element * * @return {Element} * @method createEl */ MenuButton.prototype.createEl = function createEl() { return _ClickableComponent.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MenuButton.prototype.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return 'vjs-menu-button ' + menuButtonClass + ' ' + _ClickableComponent.prototype.buildCSSClass.call(this); }; /** * When you click the button it adds focus, which * will show the menu indefinitely. * So we'll remove focus when the mouse leaves the button. * Focus is needed for tab navigation. * Allow sub components to stack CSS class names * * @method handleClick */ MenuButton.prototype.handleClick = function handleClick() { this.one('mouseout', Fn.bind(this, function () { this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } }; /** * Handle key press on menu * * @param {Object} event Key press event * @method handleKeyPress */ MenuButton.prototype.handleKeyPress = function handleKeyPress(event) { // Escape (27) key or Tab (9) key unpress the 'button' if (event.which === 27 || event.which === 9) { if (this.buttonPressed_) { this.unpressButton(); } // Don't preventDefault for Tab key - we still want to lose focus if (event.which !== 9) { event.preventDefault(); } // Up (38) key or Down (40) key press the 'button' } else if (event.which === 38 || event.which === 40) { if (!this.buttonPressed_) { this.pressButton(); event.preventDefault(); } } else { _ClickableComponent.prototype.handleKeyPress.call(this, event); } }; /** * Handle key press on submenu * * @param {Object} event Key press event * @method handleSubmenuKeyPress */ MenuButton.prototype.handleSubmenuKeyPress = function handleSubmenuKeyPress(event) { // Escape (27) key or Tab (9) key unpress the 'button' if (event.which === 27 || event.which === 9) { if (this.buttonPressed_) { this.unpressButton(); } // Don't preventDefault for Tab key - we still want to lose focus if (event.which !== 9) { event.preventDefault(); } } }; /** * Makes changes based on button pressed * * @method pressButton */ MenuButton.prototype.pressButton = function pressButton() { this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-expanded', true); this.menu.focus(); // set the focus into the submenu }; /** * Makes changes based on button unpressed * * @method unpressButton */ MenuButton.prototype.unpressButton = function unpressButton() { this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-expanded', false); this.el_.focus(); // Set focus back to this menu button }; return MenuButton; })(_clickableComponentJs2['default']); _componentJs2['default'].registerComponent('MenuButton', MenuButton); exports['default'] = MenuButton; module.exports = exports['default']; },{"../clickable-component.js":65,"../component.js":67,"../utils/dom.js":132,"../utils/fn.js":134,"../utils/to-title-case.js":141,"./menu.js":106}],105:[function(_dereq_,module,exports){ /** * @file menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _clickableComponentJs = _dereq_('../clickable-component.js'); var _clickableComponentJs2 = _interopRequireDefault(_clickableComponentJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * The component for a menu item. `<li>` * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuItem */ var MenuItem = (function (_ClickableComponent) { _inherits(MenuItem, _ClickableComponent); function MenuItem(player, options) { _classCallCheck(this, MenuItem); _ClickableComponent.call(this, player, options); this.selectable = options['selectable']; this.selected(options['selected']); if (this.selectable) { // TODO: May need to be either menuitemcheckbox or menuitemradio, // and may need logical grouping of menu items. this.el_.setAttribute('role', 'menuitemcheckbox'); } else { this.el_.setAttribute('role', 'menuitem'); } } /** * Create the component's DOM element * * @param {String=} type Desc * @param {Object=} props Desc * @return {Element} * @method createEl */ MenuItem.prototype.createEl = function createEl(type, props, attrs) { return _ClickableComponent.prototype.createEl.call(this, 'li', _objectAssign2['default']({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_['label']), tabIndex: -1 }, props), attrs); }; /** * Handle a click on the menu item, and set it to selected * * @method handleClick */ MenuItem.prototype.handleClick = function handleClick() { this.selected(true); }; /** * Set this menu item as selected or not * * @param {Boolean} selected * @method selected */ MenuItem.prototype.selected = function selected(_selected) { if (this.selectable) { if (_selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-checked', true); // aria-checked isn't fully supported by browsers/screen readers, // so indicate selected state to screen reader in the control text. this.controlText(', selected'); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-checked', false); // Indicate un-selected state to screen reader // Note that a space clears out the selected state text this.controlText(' '); } } }; return MenuItem; })(_clickableComponentJs2['default']); _componentJs2['default'].registerComponent('MenuItem', MenuItem); exports['default'] = MenuItem; module.exports = exports['default']; },{"../clickable-component.js":65,"../component.js":67,"object.assign":45}],106:[function(_dereq_,module,exports){ /** * @file menu.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsEventsJs = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @extends Component * @class Menu */ var Menu = (function (_Component) { _inherits(Menu, _Component); function Menu(player, options) { _classCallCheck(this, Menu); _Component.call(this, player, options); this.focusedChild_ = -1; this.on('keydown', this.handleKeyPress); } /** * Add a menu item to the menu * * @param {Object|String} component Component or component type to add * @method addItem */ Menu.prototype.addItem = function addItem(component) { this.addChild(component); component.on('click', Fn.bind(this, function () { this.unlockShowing(); //TODO: Need to set keyboard focus back to the menuButton })); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Menu.prototype.createEl = function createEl() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = Dom.createEl(contentElType, { className: 'vjs-menu-content' }); this.contentEl_.setAttribute('role', 'menu'); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.setAttribute('role', 'presentation'); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant Events.on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; /** * Handle key press for menu * * @param {Object} event Event object * @method handleKeyPress */ Menu.prototype.handleKeyPress = function handleKeyPress(event) { if (event.which === 37 || event.which === 40) { // Left and Down Arrows event.preventDefault(); this.stepForward(); } else if (event.which === 38 || event.which === 39) { // Up and Right Arrows event.preventDefault(); this.stepBack(); } }; /** * Move to next (lower) menu item for keyboard users * * @method stepForward */ Menu.prototype.stepForward = function stepForward() { var stepChild = 0; if (this.focusedChild_ !== undefined) { stepChild = this.focusedChild_ + 1; } this.focus(stepChild); }; /** * Move to previous (higher) menu item for keyboard users * * @method stepBack */ Menu.prototype.stepBack = function stepBack() { var stepChild = 0; if (this.focusedChild_ !== undefined) { stepChild = this.focusedChild_ - 1; } this.focus(stepChild); }; /** * Set focus on a menu item in the menu * * @param {Object|String} item Index of child item set focus on * @method focus */ Menu.prototype.focus = function focus() { var item = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; var children = this.children().slice(); var haveTitle = children[0].className && /vjs-menu-title/.test(children[0].className); if (haveTitle) { children.shift(); } if (children.length > 0) { if (item < 0) { item = 0; } else if (item >= children.length) { item = children.length - 1; } this.focusedChild_ = item; children[item].el_.focus(); } }; return Menu; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Menu', Menu); exports['default'] = Menu; module.exports = exports['default']; },{"../component.js":67,"../utils/dom.js":132,"../utils/events.js":133,"../utils/fn.js":134}],107:[function(_dereq_,module,exports){ /** * @file modal-dialog.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _utilsDom = _dereq_('./utils/dom'); var Dom = _interopRequireWildcard(_utilsDom); var _utilsFn = _dereq_('./utils/fn'); var Fn = _interopRequireWildcard(_utilsFn); var _utilsLog = _dereq_('./utils/log'); var _utilsLog2 = _interopRequireDefault(_utilsLog); var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _closeButton = _dereq_('./close-button'); var _closeButton2 = _interopRequireDefault(_closeButton); var MODAL_CLASS_NAME = 'vjs-modal-dialog'; var ESC = 27; /** * The `ModalDialog` displays over the video and its controls, which blocks * interaction with the player until it is closed. * * Modal dialogs include a "Close" button and will close when that button * is activated - or when ESC is pressed anywhere. * * @extends Component * @class ModalDialog */ var ModalDialog = (function (_Component) { _inherits(ModalDialog, _Component); /** * Constructor for modals. * * @param {Player} player * @param {Object} [options] * @param {Mixed} [options.content=undefined] * Provide customized content for this modal. * * @param {String} [options.description] * A text description for the modal, primarily for accessibility. * * @param {Boolean} [options.fillAlways=false] * Normally, modals are automatically filled only the first time * they open. This tells the modal to refresh its content * every time it opens. * * @param {String} [options.label] * A text label for the modal, primarily for accessibility. * * @param {Boolean} [options.temporary=true] * If `true`, the modal can only be opened once; it will be * disposed as soon as it's closed. * * @param {Boolean} [options.uncloseable=false] * If `true`, the user will not be able to close the modal * through the UI in the normal ways. Programmatic closing is * still possible. * */ function ModalDialog(player, options) { _classCallCheck(this, ModalDialog); _Component.call(this, player, options); this.opened_ = this.hasBeenOpened_ = this.hasBeenFilled_ = false; this.closeable(!this.options_.uncloseable); this.content(this.options_.content); // Make sure the contentEl is defined AFTER any children are initialized // because we only want the contents of the modal in the contentEl // (not the UI elements like the close button). this.contentEl_ = Dom.createEl('div', { className: MODAL_CLASS_NAME + '-content' }, { role: 'document' }); this.descEl_ = Dom.createEl('p', { className: MODAL_CLASS_NAME + '-description vjs-offscreen', id: this.el().getAttribute('aria-describedby') }); Dom.textContent(this.descEl_, this.description()); this.el_.appendChild(this.descEl_); this.el_.appendChild(this.contentEl_); } /* * Modal dialog default options. * * @type {Object} * @private */ /** * Create the modal's DOM element * * @method createEl * @return {Element} */ ModalDialog.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass(), tabIndex: -1 }, { 'aria-describedby': this.id() + '_description', 'aria-hidden': 'true', 'aria-label': this.label(), role: 'dialog' }); }; /** * Build the modal's CSS class. * * @method buildCSSClass * @return {String} */ ModalDialog.prototype.buildCSSClass = function buildCSSClass() { return MODAL_CLASS_NAME + ' vjs-hidden ' + _Component.prototype.buildCSSClass.call(this); }; /** * Handles key presses on the document, looking for ESC, which closes * the modal. * * @method handleKeyPress * @param {Event} e */ ModalDialog.prototype.handleKeyPress = function handleKeyPress(e) { if (e.which === ESC && this.closeable()) { this.close(); } }; /** * Returns the label string for this modal. Primarily used for accessibility. * * @return {String} */ ModalDialog.prototype.label = function label() { return this.options_.label || this.localize('Modal Window'); }; /** * Returns the description string for this modal. Primarily used for * accessibility. * * @return {String} */ ModalDialog.prototype.description = function description() { var desc = this.options_.description || this.localize('This is a modal window.'); // Append a universal closeability message if the modal is closeable. if (this.closeable()) { desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.'); } return desc; }; /** * Opens the modal. * * @method open * @return {ModalDialog} */ ModalDialog.prototype.open = function open() { if (!this.opened_) { var player = this.player(); this.trigger('beforemodalopen'); this.opened_ = true; // Fill content if the modal has never opened before and // never been filled. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) { this.fill(); } // If the player was playing, pause it and take note of its previously // playing state. this.wasPlaying_ = !player.paused(); if (this.wasPlaying_) { player.pause(); } if (this.closeable()) { this.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); } player.controls(false); this.show(); this.el().setAttribute('aria-hidden', 'false'); this.trigger('modalopen'); this.hasBeenOpened_ = true; } return this; }; /** * Whether or not the modal is opened currently. * * @method opened * @param {Boolean} [value] * If given, it will open (`true`) or close (`false`) the modal. * * @return {Boolean} */ ModalDialog.prototype.opened = function opened(value) { if (typeof value === 'boolean') { this[value ? 'open' : 'close'](); } return this.opened_; }; /** * Closes the modal. * * @method close * @return {ModalDialog} */ ModalDialog.prototype.close = function close() { if (this.opened_) { var player = this.player(); this.trigger('beforemodalclose'); this.opened_ = false; if (this.wasPlaying_) { player.play(); } if (this.closeable()) { this.off(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); } player.controls(true); this.hide(); this.el().setAttribute('aria-hidden', 'true'); this.trigger('modalclose'); if (this.options_.temporary) { this.dispose(); } } return this; }; /** * Whether or not the modal is closeable via the UI. * * @method closeable * @param {Boolean} [value] * If given as a Boolean, it will set the `closeable` option. * * @return {Boolean} */ ModalDialog.prototype.closeable = function closeable(value) { if (typeof value === 'boolean') { var closeable = this.closeable_ = !!value; var _close = this.getChild('closeButton'); // If this is being made closeable and has no close button, add one. if (closeable && !_close) { // The close button should be a child of the modal - not its // content element, so temporarily change the content element. var temp = this.contentEl_; this.contentEl_ = this.el_; _close = this.addChild('closeButton'); this.contentEl_ = temp; this.on(_close, 'close', this.close); } // If this is being made uncloseable and has a close button, remove it. if (!closeable && _close) { this.off(_close, 'close', this.close); this.removeChild(_close); _close.dispose(); } } return this.closeable_; }; /** * Fill the modal's content element with the modal's "content" option. * * The content element will be emptied before this change takes place. * * @method fill * @return {ModalDialog} */ ModalDialog.prototype.fill = function fill() { return this.fillWith(this.content()); }; /** * Fill the modal's content element with arbitrary content. * * The content element will be emptied before this change takes place. * * @method fillWith * @param {Mixed} [content] * The same rules apply to this as apply to the `content` option. * * @return {ModalDialog} */ ModalDialog.prototype.fillWith = function fillWith(content) { var contentEl = this.contentEl(); var parentEl = contentEl.parentNode; var nextSiblingEl = contentEl.nextSibling; this.trigger('beforemodalfill'); this.hasBeenFilled_ = true; // Detach the content element from the DOM before performing // manipulation to avoid modifying the live DOM multiple times. parentEl.removeChild(contentEl); this.empty(); Dom.insertContent(contentEl, content); this.trigger('modalfill'); // Re-inject the re-filled content element. if (nextSiblingEl) { parentEl.insertBefore(contentEl, nextSiblingEl); } else { parentEl.appendChild(contentEl); } return this; }; /** * Empties the content element. * * This happens automatically anytime the modal is filled. * * @method empty * @return {ModalDialog} */ ModalDialog.prototype.empty = function empty() { this.trigger('beforemodalempty'); Dom.emptyEl(this.contentEl()); this.trigger('modalempty'); return this; }; /** * Gets or sets the modal content, which gets normalized before being * rendered into the DOM. * * This does not update the DOM or fill the modal, but it is called during * that process. * * @method content * @param {Mixed} [value] * If defined, sets the internal content value to be used on the * next call(s) to `fill`. This value is normalized before being * inserted. To "clear" the internal content value, pass `null`. * * @return {Mixed} */ ModalDialog.prototype.content = function content(value) { if (typeof value !== 'undefined') { this.content_ = value; } return this.content_; }; return ModalDialog; })(_component2['default']); ModalDialog.prototype.options_ = { temporary: true }; _component2['default'].registerComponent('ModalDialog', ModalDialog); exports['default'] = ModalDialog; module.exports = exports['default']; },{"./close-button":66,"./component":67,"./utils/dom":132,"./utils/fn":134,"./utils/log":137,"global/document":1}],108:[function(_dereq_,module,exports){ /** * @file player.js */ // Subclasses Component 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js'); var _utilsBufferJs = _dereq_('./utils/buffer.js'); var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js'); var stylesheet = _interopRequireWildcard(_utilsStylesheetJs); var _fullscreenApiJs = _dereq_('./fullscreen-api.js'); var _fullscreenApiJs2 = _interopRequireDefault(_fullscreenApiJs); var _mediaErrorJs = _dereq_('./media-error.js'); var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs); var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple'); var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); var _tracksTextTrackListConverterJs = _dereq_('./tracks/text-track-list-converter.js'); var _tracksTextTrackListConverterJs2 = _interopRequireDefault(_tracksTextTrackListConverterJs); // Include required child components (importing also registers them) var _techLoaderJs = _dereq_('./tech/loader.js'); var _techLoaderJs2 = _interopRequireDefault(_techLoaderJs); var _posterImageJs = _dereq_('./poster-image.js'); var _posterImageJs2 = _interopRequireDefault(_posterImageJs); var _tracksTextTrackDisplayJs = _dereq_('./tracks/text-track-display.js'); var _tracksTextTrackDisplayJs2 = _interopRequireDefault(_tracksTextTrackDisplayJs); var _loadingSpinnerJs = _dereq_('./loading-spinner.js'); var _loadingSpinnerJs2 = _interopRequireDefault(_loadingSpinnerJs); var _bigPlayButtonJs = _dereq_('./big-play-button.js'); var _bigPlayButtonJs2 = _interopRequireDefault(_bigPlayButtonJs); var _controlBarControlBarJs = _dereq_('./control-bar/control-bar.js'); var _controlBarControlBarJs2 = _interopRequireDefault(_controlBarControlBarJs); var _errorDisplayJs = _dereq_('./error-display.js'); var _errorDisplayJs2 = _interopRequireDefault(_errorDisplayJs); var _tracksTextTrackSettingsJs = _dereq_('./tracks/text-track-settings.js'); var _tracksTextTrackSettingsJs2 = _interopRequireDefault(_tracksTextTrackSettingsJs); var _modalDialog = _dereq_('./modal-dialog'); var _modalDialog2 = _interopRequireDefault(_modalDialog); // Require html5 tech, at least for disposing the original video tag var _techTechJs = _dereq_('./tech/tech.js'); var _techTechJs2 = _interopRequireDefault(_techTechJs); var _techHtml5Js = _dereq_('./tech/html5.js'); var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js); /** * An instance of the `Player` class is created when any of the Video.js setup methods are used to initialize a video. * ```js * var myPlayer = videojs('example_video_1'); * ``` * In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready. * ```html * <video id="example_video_1" data-setup='{}' controls> * <source src="my-source.mp4" type="video/mp4"> * </video> * ``` * After an instance has been created it can be accessed globally using `Video('example_video_1')`. * * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class Player */ var Player = (function (_Component) { _inherits(Player, _Component); /** * player's constructor function * * @constructs * @method init * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Player options * @param {Function=} ready Ready callback function */ function Player(tag, options, ready) { var _this = this; _classCallCheck(this, Player); // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + Guid.newGUID(); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = _objectAssign2['default'](Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up // player properties first, and can't use `this` before `super()` options.initChildren = false; // Same with creating the element options.createEl = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Run base component initializing with new options _Component.call(this, null, options, ready); // if the global option object was accidentally blown away by // someone, bail early with an informative error if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) { throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?'); } this.tag = tag; // Store the original tag used to set options // Store the tag attributes used to restore html5 element this.tagAttributes = tag && Dom.getElAttributes(tag); // Update current language this.language(this.options_.language); // Update Supported Languages if (options.languages) { (function () { // Normalise player option languages to lowercase var languagesToLower = {}; Object.getOwnPropertyNames(options.languages).forEach(function (name) { languagesToLower[name.toLowerCase()] = options.languages[name]; }); _this.languages_ = languagesToLower; })(); } else { this.languages_ = Player.prototype.options_.languages; } // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options.poster || ''; // Set controls this.controls_ = !!options.controls; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; /* * Store the internal state of scrubbing * * @private * @return {Boolean} True if the user is scrubbing */ this.scrubbing_ = false; this.el_ = this.createEl(); // We also want to pass the original player options to each component and plugin // as well so they don't need to reach back into the player for options later. // We also need to do another copy of this.options_ so we don't end up with // an infinite loop. var playerOptionsCopy = _utilsMergeOptionsJs2['default'](this.options_); // Load plugins if (options.plugins) { (function () { var plugins = options.plugins; Object.getOwnPropertyNames(plugins).forEach(function (name) { if (typeof this[name] === 'function') { this[name](plugins[name]); } else { _utilsLogJs2['default'].error('Unable to find plugin:', name); } }, _this); })(); } this.options_.playerOptions = playerOptionsCopy; this.initChildren(); // Set isAudio based on whether or not an audio tag was used this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } if (this.isAudio()) { this.addClass('vjs-audio'); } if (this.flexNotSupported_()) { this.addClass('vjs-no-flex'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (browser.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // iOS Safari has broken hover handling if (!browser.IS_IOS) { this.addClass('vjs-workinghover'); } // Make player easily findable by ID Player.players[this.id_] = this; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed this.userActive(true); this.reportUserActivity(); this.listenForUserActivity_(); this.on('fullscreenchange', this.handleFullscreenChange_); this.on('stageclick', this.handleStageClick_); } /* * Global player list * * @type {Object} */ /** * Destroys the video player and does any necessary cleanup * ```js * myPlayer.dispose(); * ``` * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. * * @method dispose */ Player.prototype.dispose = function dispose() { this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); if (this.styleEl_ && this.styleEl_.parentNode) { this.styleEl_.parentNode.removeChild(this.styleEl_); } // Kill reference to this player Player.players[this.id_] = null; if (this.tag && this.tag.player) { this.tag.player = null; } if (this.el_ && this.el_.player) { this.el_.player = null; } if (this.tech_) { this.tech_.dispose(); } _Component.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Player.prototype.createEl = function createEl() { var el = this.el_ = _Component.prototype.createEl.call(this, 'div'); var tag = this.tag; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag var attrs = Dom.getElAttributes(tag); Object.getOwnPropertyNames(attrs).forEach(function (attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr === 'class') { el.className = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.playerId = tag.id; tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag.player = el.player = this; // Default state of video is paused this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height // of the player in a way that's still overrideable by CSS, just like the // video element this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions'); var defaultsStyleEl = Dom.$('.vjs-styles-defaults'); var head = Dom.$('head'); head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild); // Pass in the width/height/aspectRatio options which will update the style el this.width(this.options_.width); this.height(this.options_.height); this.fluid(this.options_.fluid); this.aspectRatio(this.options_.aspectRatio); // insertElFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode) { tag.parentNode.insertBefore(el, tag); } // insert the tag as the first child of the player element // then manually add it to the children array so that this.addChild // will work properly for other components Dom.insertElFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. this.children_.unshift(tag); this.el_ = el; return el; }; /** * Get/set player width * * @param {Number=} value Value for width * @return {Number} Width when getting * @method width */ Player.prototype.width = function width(value) { return this.dimension('width', value); }; /** * Get/set player height * * @param {Number=} value Value for height * @return {Number} Height when getting * @method height */ Player.prototype.height = function height(value) { return this.dimension('height', value); }; /** * Get/set dimension for player * * @param {String} dimension Either width or height * @param {Number=} value Value for dimension * @return {Component} * @method dimension */ Player.prototype.dimension = function dimension(_dimension, value) { var privDimension = _dimension + '_'; if (value === undefined) { return this[privDimension] || 0; } if (value === '') { // If an empty string is given, reset the dimension to be automatic this[privDimension] = undefined; } else { var parsedVal = parseFloat(value); if (isNaN(parsedVal)) { _utilsLogJs2['default'].error('Improper value "' + value + '" supplied for for ' + _dimension); return this; } this[privDimension] = parsedVal; } this.updateStyleEl_(); return this; }; /** * Add/remove the vjs-fluid class * * @param {Boolean} bool Value of true adds the class, value of false removes the class * @method fluid */ Player.prototype.fluid = function fluid(bool) { if (bool === undefined) { return !!this.fluid_; } this.fluid_ = !!bool; if (bool) { this.addClass('vjs-fluid'); } else { this.removeClass('vjs-fluid'); } }; /** * Get/Set the aspect ratio * * @param {String=} ratio Aspect ratio for player * @return aspectRatio * @method aspectRatio */ Player.prototype.aspectRatio = function aspectRatio(ratio) { if (ratio === undefined) { return this.aspectRatio_; } // Check for width:height format if (!/^\d+\:\d+$/.test(ratio)) { throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.'); } this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode, // because in fixed mode you could calculate width and height yourself. this.fluid(true); this.updateStyleEl_(); }; /** * Update styles of the player element (height, width and aspect ratio) * * @method updateStyleEl_ */ Player.prototype.updateStyleEl_ = function updateStyleEl_() { var width = undefined; var height = undefined; var aspectRatio = undefined; var idClass = undefined; // The aspect ratio is either used directly or to calculate width and height. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') { // Use any aspectRatio that's been specifically set aspectRatio = this.aspectRatio_; } else if (this.videoWidth()) { // Otherwise try to get the aspect ratio from the video metadata aspectRatio = this.videoWidth() + ':' + this.videoHeight(); } else { // Or use a default. The video element's is 2:1, but 16:9 is more common. aspectRatio = '16:9'; } // Get the ratio as a decimal we can use to calculate dimensions var ratioParts = aspectRatio.split(':'); var ratioMultiplier = ratioParts[1] / ratioParts[0]; if (this.width_ !== undefined) { // Use any width that's been specifically set width = this.width_; } else if (this.height_ !== undefined) { // Or calulate the width from the aspect ratio if a height has been set width = this.height_ / ratioMultiplier; } else { // Or use the video's metadata, or use the video el's default of 300 width = this.videoWidth() || 300; } if (this.height_ !== undefined) { // Use any height that's been specifically set height = this.height_; } else { // Otherwise calculate the height from the ratio and the width height = width * ratioMultiplier; } // Ensure the CSS class is valid by starting with an alpha character if (/^[^a-zA-Z]/.test(this.id())) { idClass = 'dimensions-' + this.id(); } else { idClass = this.id() + '-dimensions'; } // Ensure the right class is still on the player for the style element this.addClass(idClass); stylesheet.setTextContent(this.styleEl_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n '); }; /** * Load the Media Playback Technology (tech) * Load/Create an instance of playback technology including element and API methods * And append playback element in player div. * * @param {String} techName Name of the playback technology * @param {String} source Video source * @method loadTech_ * @private */ Player.prototype.loadTech_ = function loadTech_(techName, source) { // Pause and remove current playback technology if (this.tech_) { this.unloadTech_(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { _techTechJs2['default'].getTech('Html5').disposeMediaElement(this.tag); this.tag.player = null; this.tag = null; } this.techName_ = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; // Grab tech-specific options from player options and add source and parent element to use. var techOptions = _objectAssign2['default']({ 'nativeControlsForTouch': this.options_.nativeControlsForTouch, 'source': source, 'playerId': this.id(), 'techId': this.id() + '_' + techName + '_api', 'textTracks': this.textTracks_, 'autoplay': this.options_.autoplay, 'preload': this.options_.preload, 'loop': this.options_.loop, 'muted': this.options_.muted, 'poster': this.poster(), 'language': this.language(), 'vtt.js': this.options_['vtt.js'] }, this.options_[techName.toLowerCase()]); if (this.tag) { techOptions.tag = this.tag; } if (source) { this.currentType_ = source.type; if (source.src === this.cache_.src && this.cache_.currentTime > 0) { techOptions.startTime = this.cache_.currentTime; } this.cache_.src = source.src; } // Initialize tech instance var techComponent = _techTechJs2['default'].getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!techComponent) { techComponent = _componentJs2['default'].getComponent(techName); } this.tech_ = new techComponent(techOptions); // player.triggerReady is always async, so don't need this to be async this.tech_.ready(Fn.bind(this, this.handleTechReady_), true); _tracksTextTrackListConverterJs2['default'].jsonToTextTracks(this.textTracksJson_ || [], this.tech_); // Listen to all HTML5-defined events and trigger them on the player this.on(this.tech_, 'loadstart', this.handleTechLoadStart_); this.on(this.tech_, 'waiting', this.handleTechWaiting_); this.on(this.tech_, 'canplay', this.handleTechCanPlay_); this.on(this.tech_, 'canplaythrough', this.handleTechCanPlayThrough_); this.on(this.tech_, 'playing', this.handleTechPlaying_); this.on(this.tech_, 'ended', this.handleTechEnded_); this.on(this.tech_, 'seeking', this.handleTechSeeking_); this.on(this.tech_, 'seeked', this.handleTechSeeked_); this.on(this.tech_, 'play', this.handleTechPlay_); this.on(this.tech_, 'firstplay', this.handleTechFirstPlay_); this.on(this.tech_, 'pause', this.handleTechPause_); this.on(this.tech_, 'progress', this.handleTechProgress_); this.on(this.tech_, 'durationchange', this.handleTechDurationChange_); this.on(this.tech_, 'fullscreenchange', this.handleTechFullscreenChange_); this.on(this.tech_, 'error', this.handleTechError_); this.on(this.tech_, 'suspend', this.handleTechSuspend_); this.on(this.tech_, 'abort', this.handleTechAbort_); this.on(this.tech_, 'emptied', this.handleTechEmptied_); this.on(this.tech_, 'stalled', this.handleTechStalled_); this.on(this.tech_, 'loadedmetadata', this.handleTechLoadedMetaData_); this.on(this.tech_, 'loadeddata', this.handleTechLoadedData_); this.on(this.tech_, 'timeupdate', this.handleTechTimeUpdate_); this.on(this.tech_, 'ratechange', this.handleTechRateChange_); this.on(this.tech_, 'volumechange', this.handleTechVolumeChange_); this.on(this.tech_, 'texttrackchange', this.handleTechTextTrackChange_); this.on(this.tech_, 'loadedmetadata', this.updateStyleEl_); this.on(this.tech_, 'posterchange', this.handleTechPosterChange_); this.usingNativeControls(this.techGet_('controls')); if (this.controls() && !this.usingNativeControls()) { this.addTechControlsListeners_(); } // Add the tech element in the DOM if it was not already there // Make sure to not insert the original video element if using Html5 if (this.tech_.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) { Dom.insertElFirst(this.tech_.el(), this.el()); } // Get rid of the original video tag reference after the first tech is loaded if (this.tag) { this.tag.player = null; this.tag = null; } }; /** * Unload playback technology * * @method unloadTech_ * @private */ Player.prototype.unloadTech_ = function unloadTech_() { // Save the current text tracks so that we can reuse the same text tracks with the next tech this.textTracks_ = this.textTracks(); this.textTracksJson_ = _tracksTextTrackListConverterJs2['default'].textTracksToJson(this.tech_); this.isReady_ = false; this.tech_.dispose(); this.tech_ = false; }; /** * Return a reference to the current tech. * It will only return a reference to the tech if given an object with the * `IWillNotUseThisInPlugins` property on it. This is try and prevent misuse * of techs by plugins. * * @param {Object} * @return {Object} The Tech * @method tech */ Player.prototype.tech = function tech(safety) { if (safety && safety.IWillNotUseThisInPlugins) { return this.tech_; } var errorText = '\n Please make sure that you are not using this inside of a plugin.\n To disable this alert and error, please pass in an object with\n `IWillNotUseThisInPlugins` to the `tech` method. See\n https://github.com/videojs/video.js/issues/2617 for more info.\n '; _globalWindow2['default'].alert(errorText); throw new Error(errorText); }; /** * Set up click and touch listeners for the playback element * * On desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls is done by toggling the user state between active and * inactive) * A tap can signal that a user has become active, or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold * on any controls will still keep the user active * * @private * @method addTechControlsListeners_ */ Player.prototype.addTechControlsListeners_ = function addTechControlsListeners_() { // Make sure to remove all the previous listeners in case we are called multiple times. this.removeTechControlsListeners_(); // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on(this.tech_, 'mousedown', this.handleTechClick_); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on(this.tech_, 'touchstart', this.handleTechTouchStart_); this.on(this.tech_, 'touchmove', this.handleTechTouchMove_); this.on(this.tech_, 'touchend', this.handleTechTouchEnd_); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on(this.tech_, 'tap', this.handleTechTap_); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. * * @method removeTechControlsListeners_ * @private */ Player.prototype.removeTechControlsListeners_ = function removeTechControlsListeners_() { // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off(this.tech_, 'tap', this.handleTechTap_); this.off(this.tech_, 'touchstart', this.handleTechTouchStart_); this.off(this.tech_, 'touchmove', this.handleTechTouchMove_); this.off(this.tech_, 'touchend', this.handleTechTouchEnd_); this.off(this.tech_, 'mousedown', this.handleTechClick_); }; /** * Player waits for the tech to be ready * * @method handleTechReady_ * @private */ Player.prototype.handleTechReady_ = function handleTechReady_() { this.triggerReady(); // Keep the same volume as before if (this.cache_.volume) { this.techCall_('setVolume', this.cache_.volume); } // Look if the tech found a higher resolution poster while loading this.handleTechPosterChange_(); // Update the duration if available this.handleTechDurationChange_(); // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly if (this.src() && this.tag && this.options_.autoplay && this.paused()) { delete this.tag.poster; // Chrome Fix. Fixed in Chrome v16. this.play(); } }; /** * Fired when the user agent begins looking for media data * * @private * @method handleTechLoadStart_ */ Player.prototype.handleTechLoadStart_ = function handleTechLoadStart_() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { this.trigger('loadstart'); this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.trigger('loadstart'); } }; /** * Add/remove the vjs-has-started class * * @param {Boolean} hasStarted The value of true adds the class the value of false remove the class * @return {Boolean} Boolean value if has started * @private * @method hasStarted */ Player.prototype.hasStarted = function hasStarted(_hasStarted) { if (_hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== _hasStarted) { this.hasStarted_ = _hasStarted; if (_hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return !!this.hasStarted_; }; /** * Fired whenever the media begins or resumes playback * * @private * @method handleTechPlay_ */ Player.prototype.handleTechPlay_ = function handleTechPlay_() { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play this.hasStarted(true); this.trigger('play'); }; /** * Fired whenever the media begins waiting * * @private * @method handleTechWaiting_ */ Player.prototype.handleTechWaiting_ = function handleTechWaiting_() { var _this2 = this; this.addClass('vjs-waiting'); this.trigger('waiting'); this.one('timeupdate', function () { return _this2.removeClass('vjs-waiting'); }); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @private * @method handleTechCanPlay_ */ Player.prototype.handleTechCanPlay_ = function handleTechCanPlay_() { this.removeClass('vjs-waiting'); this.trigger('canplay'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @private * @method handleTechCanPlayThrough_ */ Player.prototype.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() { this.removeClass('vjs-waiting'); this.trigger('canplaythrough'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @private * @method handleTechPlaying_ */ Player.prototype.handleTechPlaying_ = function handleTechPlaying_() { this.removeClass('vjs-waiting'); this.trigger('playing'); }; /** * Fired whenever the player is jumping to a new time * * @private * @method handleTechSeeking_ */ Player.prototype.handleTechSeeking_ = function handleTechSeeking_() { this.addClass('vjs-seeking'); this.trigger('seeking'); }; /** * Fired when the player has finished jumping to a new time * * @private * @method handleTechSeeked_ */ Player.prototype.handleTechSeeked_ = function handleTechSeeked_() { this.removeClass('vjs-seeking'); this.trigger('seeked'); }; /** * Fired the first time a video is played * Not part of the HLS spec, and we're not sure if this is the best * implementation yet, so use sparingly. If you don't have a reason to * prevent playback, use `myPlayer.one('play');` instead. * * @private * @method handleTechFirstPlay_ */ Player.prototype.handleTechFirstPlay_ = function handleTechFirstPlay_() { //If the first starttime attribute is specified //then we will start at the given offset in seconds if (this.options_.starttime) { this.currentTime(this.options_.starttime); } this.addClass('vjs-has-started'); this.trigger('firstplay'); }; /** * Fired whenever the media has been paused * * @private * @method handleTechPause_ */ Player.prototype.handleTechPause_ = function handleTechPause_() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.trigger('pause'); }; /** * Fired while the user agent is downloading media data * * @private * @method handleTechProgress_ */ Player.prototype.handleTechProgress_ = function handleTechProgress_() { this.trigger('progress'); }; /** * Fired when the end of the media resource is reached (currentTime == duration) * * @private * @method handleTechEnded_ */ Player.prototype.handleTechEnded_ = function handleTechEnded_() { this.addClass('vjs-ended'); if (this.options_.loop) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } this.trigger('ended'); }; /** * Fired when the duration of the media resource is first known or changed * * @private * @method handleTechDurationChange_ */ Player.prototype.handleTechDurationChange_ = function handleTechDurationChange_() { this.duration(this.techGet_('duration')); }; /** * Handle a click on the media element to play/pause * * @param {Object=} event Event object * @private * @method handleTechClick_ */ Player.prototype.handleTechClick_ = function handleTechClick_(event) { // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) return; // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.controls()) { if (this.paused()) { this.play(); } else { this.pause(); } } }; /** * Handle a tap on the media element. It will toggle the user * activity state, which hides and shows the controls. * * @private * @method handleTechTap_ */ Player.prototype.handleTechTap_ = function handleTechTap_() { this.userActive(!this.userActive()); }; /** * Handle touch to start * * @private * @method handleTechTouchStart_ */ Player.prototype.handleTechTouchStart_ = function handleTechTouchStart_() { this.userWasActive = this.userActive(); }; /** * Handle touch to move * * @private * @method handleTechTouchMove_ */ Player.prototype.handleTechTouchMove_ = function handleTechTouchMove_() { if (this.userWasActive) { this.reportUserActivity(); } }; /** * Handle touch to end * * @private * @method handleTechTouchEnd_ */ Player.prototype.handleTechTouchEnd_ = function handleTechTouchEnd_(event) { // Stop the mouse events from also happening event.preventDefault(); }; /** * Fired when the player switches in or out of fullscreen mode * * @private * @method handleFullscreenChange_ */ Player.prototype.handleFullscreenChange_ = function handleFullscreenChange_() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * native click events on the SWF aren't triggered on IE11, Win8.1RT * use stageclick events triggered from inside the SWF instead * * @private * @method handleStageClick_ */ Player.prototype.handleStageClick_ = function handleStageClick_() { this.reportUserActivity(); }; /** * Handle Tech Fullscreen Change * * @private * @method handleTechFullscreenChange_ */ Player.prototype.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) { if (data) { this.isFullscreen(data.isFullscreen); } this.trigger('fullscreenchange'); }; /** * Fires when an error occurred during the loading of an audio/video * * @private * @method handleTechError_ */ Player.prototype.handleTechError_ = function handleTechError_() { var error = this.tech_.error(); this.error(error && error.code); }; /** * Fires when the browser is intentionally not getting media data * * @private * @method handleTechSuspend_ */ Player.prototype.handleTechSuspend_ = function handleTechSuspend_() { this.trigger('suspend'); }; /** * Fires when the loading of an audio/video is aborted * * @private * @method handleTechAbort_ */ Player.prototype.handleTechAbort_ = function handleTechAbort_() { this.trigger('abort'); }; /** * Fires when the current playlist is empty * * @private * @method handleTechEmptied_ */ Player.prototype.handleTechEmptied_ = function handleTechEmptied_() { this.trigger('emptied'); }; /** * Fires when the browser is trying to get media data, but data is not available * * @private * @method handleTechStalled_ */ Player.prototype.handleTechStalled_ = function handleTechStalled_() { this.trigger('stalled'); }; /** * Fires when the browser has loaded meta data for the audio/video * * @private * @method handleTechLoadedMetaData_ */ Player.prototype.handleTechLoadedMetaData_ = function handleTechLoadedMetaData_() { this.trigger('loadedmetadata'); }; /** * Fires when the browser has loaded the current frame of the audio/video * * @private * @method handleTechLoadedData_ */ Player.prototype.handleTechLoadedData_ = function handleTechLoadedData_() { this.trigger('loadeddata'); }; /** * Fires when the current playback position has changed * * @private * @method handleTechTimeUpdate_ */ Player.prototype.handleTechTimeUpdate_ = function handleTechTimeUpdate_() { this.trigger('timeupdate'); }; /** * Fires when the playing speed of the audio/video is changed * * @private * @method handleTechRateChange_ */ Player.prototype.handleTechRateChange_ = function handleTechRateChange_() { this.trigger('ratechange'); }; /** * Fires when the volume has been changed * * @private * @method handleTechVolumeChange_ */ Player.prototype.handleTechVolumeChange_ = function handleTechVolumeChange_() { this.trigger('volumechange'); }; /** * Fires when the text track has been changed * * @private * @method handleTechTextTrackChange_ */ Player.prototype.handleTechTextTrackChange_ = function handleTechTextTrackChange_() { this.trigger('texttrackchange'); }; /** * Get object for cached values. * * @return {Object} * @method getCache */ Player.prototype.getCache = function getCache() { return this.cache_; }; /** * Pass values to the playback tech * * @param {String=} method Method * @param {Object=} arg Argument * @private * @method techCall_ */ Player.prototype.techCall_ = function techCall_(method, arg) { // If it's not ready yet, call method when it is if (this.tech_ && !this.tech_.isReady_) { this.tech_.ready(function () { this[method](arg); }, true); // Otherwise call method now } else { try { this.tech_[method](arg); } catch (e) { _utilsLogJs2['default'](e); throw e; } } }; /** * Get calls can't wait for the tech, and sometimes don't need to. * * @param {String} method Tech method * @return {Method} * @private * @method techGet_ */ Player.prototype.techGet_ = function techGet_(method) { if (this.tech_ && this.tech_.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech_[method](); } catch (e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech_[method] === undefined) { _utilsLogJs2['default']('Video.js: ' + method + ' method not defined for ' + this.techName_ + ' playback technology.', e); } else { // When a method isn't available on the object it throws a TypeError if (e.name === 'TypeError') { _utilsLogJs2['default']('Video.js: ' + method + ' unavailable on ' + this.techName_ + ' playback technology element.', e); this.tech_.isReady_ = false; } else { _utilsLogJs2['default'](e); } } throw e; } } return; }; /** * start media playback * ```js * myPlayer.play(); * ``` * * @return {Player} self * @method play */ Player.prototype.play = function play() { this.techCall_('play'); return this; }; /** * Pause the video playback * ```js * myPlayer.pause(); * ``` * * @return {Player} self * @method pause */ Player.prototype.pause = function pause() { this.techCall_('pause'); return this; }; /** * Check if the player is paused * ```js * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * ``` * * @return {Boolean} false if the media is currently playing, or true otherwise * @method paused */ Player.prototype.paused = function paused() { // The initial state of paused should be true (in Safari it's actually false) return this.techGet_('paused') === false ? false : true; }; /** * Returns whether or not the user is "scrubbing". Scrubbing is when the user * has clicked the progress bar handle and is dragging it along the progress bar. * * @param {Boolean} isScrubbing True/false the user is scrubbing * @return {Boolean} The scrubbing status when getting * @return {Object} The player when setting * @method scrubbing */ Player.prototype.scrubbing = function scrubbing(isScrubbing) { if (isScrubbing !== undefined) { this.scrubbing_ = !!isScrubbing; if (isScrubbing) { this.addClass('vjs-scrubbing'); } else { this.removeClass('vjs-scrubbing'); } return this; } return this.scrubbing_; }; /** * Get or set the current time (in seconds) * ```js * // get * var whereYouAt = myPlayer.currentTime(); * // set * myPlayer.currentTime(120); // 2 minutes into the video * ``` * * @param {Number|String=} seconds The time to seek to * @return {Number} The time in seconds, when not setting * @return {Player} self, when the current time is set * @method currentTime */ Player.prototype.currentTime = function currentTime(seconds) { if (seconds !== undefined) { this.techCall_('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. return this.cache_.currentTime = this.techGet_('currentTime') || 0; }; /** * Get the length in time of the video in seconds * ```js * var lengthOfVideo = myPlayer.duration(); * ``` * **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @param {Number} seconds Duration when setting * @return {Number} The duration of the video in seconds when getting * @method duration */ Player.prototype.duration = function duration(seconds) { if (seconds === undefined) { return this.cache_.duration || 0; } seconds = parseFloat(seconds) || 0; // Standardize on Inifity for signaling video is live if (seconds < 0) { seconds = Infinity; } if (seconds !== this.cache_.duration) { // Cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = seconds; if (seconds === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } this.trigger('durationchange'); } return this; }; /** * Calculates how much time is left. * ```js * var timeLeft = myPlayer.remainingTime(); * ``` * Not a native video element function, but useful * * @return {Number} The time remaining in seconds * @method remainingTime */ Player.prototype.remainingTime = function remainingTime() { return this.duration() - this.currentTime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // Buffered returns a timerange object. // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with the times of the video that have been downloaded * If you just want the percent of the video that's been downloaded, * use bufferedPercent. * ```js * // Number of different ranges of time have been buffered. Usually 1. * numberOfRanges = bufferedTimeRange.length, * // Time in seconds when the first range starts. Usually 0. * firstRangeStart = bufferedTimeRange.start(0), * // Time in seconds when the first range ends * firstRangeEnd = bufferedTimeRange.end(0), * // Length in seconds of the first time range * firstRangeLength = firstRangeEnd - firstRangeStart; * ``` * * @return {Object} A mock TimeRange object (following HTML spec) * @method buffered */ Player.prototype.buffered = function buffered() { var buffered = this.techGet_('buffered'); if (!buffered || !buffered.length) { buffered = _utilsTimeRangesJs.createTimeRange(0, 0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded * ```js * var howMuchIsDownloaded = myPlayer.bufferedPercent(); * ``` * 0 means none, 1 means all. * (This method isn't in the HTML5 spec, but it's very convenient) * * @return {Number} A decimal between 0 and 1 representing the percent * @method bufferedPercent */ Player.prototype.bufferedPercent = function bufferedPercent() { return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration()); }; /** * Get the ending time of the last buffered time range * This is used in the progress bar to encapsulate all time ranges. * * @return {Number} The end of the last buffered time range * @method bufferedEnd */ Player.prototype.bufferedEnd = function bufferedEnd() { var buffered = this.buffered(), duration = this.duration(), end = buffered.end(buffered.length - 1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * ```js * // get * var howLoudIsIt = myPlayer.volume(); * // set * myPlayer.volume(0.5); // Set volume to half * ``` * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {Number} percentAsDecimal The new volume as a decimal percent * @return {Number} The current volume when getting * @return {Player} self when setting * @method volume */ Player.prototype.volume = function volume(percentAsDecimal) { var vol = undefined; if (percentAsDecimal !== undefined) { vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1 this.cache_.volume = vol; this.techCall_('setVolume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet_('volume')); return isNaN(vol) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * ```js * // get * var isVolumeMuted = myPlayer.muted(); * // set * myPlayer.muted(true); // mute the volume * ``` * * @param {Boolean=} muted True to mute, false to unmute * @return {Boolean} True if mute is on, false if not when getting * @return {Player} self when setting mute * @method muted */ Player.prototype.muted = function muted(_muted) { if (_muted !== undefined) { this.techCall_('setMuted', _muted); return this; } return this.techGet_('muted') || false; // Default to false }; // Check if current tech can support native fullscreen // (e.g. with built in controls like iOS, so not our flash swf) /** * Check to see if fullscreen is supported * * @return {Boolean} * @method supportsFullScreen */ Player.prototype.supportsFullScreen = function supportsFullScreen() { return this.techGet_('supportsFullScreen') || false; }; /** * Check if the player is in fullscreen mode * ```js * // get * var fullscreenOrNot = myPlayer.isFullscreen(); * // set * myPlayer.isFullscreen(true); // tell the player it's in fullscreen * ``` * NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen false if not when getting * @return {Player} self when setting * @method isFullscreen */ Player.prototype.isFullscreen = function isFullscreen(isFS) { if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return !!this.isFullscreen_; }; /** * Increase the size of the video to full screen * ```js * myPlayer.requestFullscreen(); * ``` * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @return {Player} self * @method requestFullscreen */ Player.prototype.requestFullscreen = function requestFullscreen() { var fsApi = _fullscreenApiJs2['default']; this.isFullscreen(true); if (fsApi.requestFullscreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events Events.on(_globalDocument2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) { this.isFullscreen(_globalDocument2['default'][fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { Events.off(_globalDocument2['default'], fsApi.fullscreenchange, documentFullscreenChange); } this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech_.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall_('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Return the video to its normal size after having been in full screen mode * ```js * myPlayer.exitFullscreen(); * ``` * * @return {Player} self * @method exitFullscreen */ Player.prototype.exitFullscreen = function exitFullscreen() { var fsApi = _fullscreenApiJs2['default']; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi.requestFullscreen) { _globalDocument2['default'][fsApi.exitFullscreen](); } else if (this.tech_.supportsFullScreen()) { this.techCall_('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. * * @method enterFullWindow */ Player.prototype.enterFullWindow = function enterFullWindow() { this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = _globalDocument2['default'].documentElement.style.overflow; // Add listener for esc key to exit fullscreen Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars _globalDocument2['default'].documentElement.style.overflow = 'hidden'; // Apply fullscreen styles Dom.addElClass(_globalDocument2['default'].body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; /** * Check for call to either exit full window or full screen on ESC key * * @param {String} event Event to check for key press * @method fullWindowOnEscKey */ Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) { if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; /** * Exit full window * * @method exitFullWindow */ Player.prototype.exitFullWindow = function exitFullWindow() { this.isFullWindow = false; Events.off(_globalDocument2['default'], 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. _globalDocument2['default'].documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles Dom.removeElClass(_globalDocument2['default'].body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; /** * Check whether the player can play a given mimetype * * @param {String} type The mimetype to check * @return {String} 'probably', 'maybe', or '' (empty string) * @method canPlayType */ Player.prototype.canPlayType = function canPlayType(type) { var can = undefined; // Loop through each playback technology in the options order for (var i = 0, j = this.options_.techOrder; i < j.length; i++) { var techName = _utilsToTitleCaseJs2['default'](j[i]); var tech = _techTechJs2['default'].getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!tech) { tech = _componentJs2['default'].getComponent(techName); } // Check if the current tech is defined before continuing if (!tech) { _utilsLogJs2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { can = tech.canPlayType(type); if (can) { return can; } } } return ''; }; /** * Select source based on tech-order or source-order * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise, * defaults to tech-order selection * * @param {Array} sources The sources for a media asset * @return {Object|Boolean} Object of source and tech order, otherwise false * @method selectSource */ Player.prototype.selectSource = function selectSource(sources) { // Get only the techs specified in `techOrder` that exist and are supported by the // current platform var techs = this.options_.techOrder.map(_utilsToTitleCaseJs2['default']).map(function (techName) { // `Component.getComponent(...)` is for support of old behavior of techs // being registered as components. // Remove once that deprecated behavior is removed. return [techName, _techTechJs2['default'].getTech(techName) || _componentJs2['default'].getComponent(techName)]; }).filter(function (_ref) { var techName = _ref[0]; var tech = _ref[1]; // Check if the current tech is defined before continuing if (tech) { // Check if the browser supports this technology return tech.isSupported(); } _utilsLogJs2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); return false; }); // Iterate over each `innerArray` element once per `outerArray` element and execute // `tester` with both. If `tester` returns a non-falsy value, exit early and return // that value. var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair(outerArray, innerArray, tester) { var found = undefined; outerArray.some(function (outerChoice) { return innerArray.some(function (innerChoice) { found = tester(outerChoice, innerChoice); if (found) { return true; } }); }); return found; }; var foundSourceAndTech = undefined; var flip = function flip(fn) { return function (a, b) { return fn(b, a); }; }; var finder = function finder(_ref2, source) { var techName = _ref2[0]; var tech = _ref2[1]; if (tech.canPlaySource(source)) { return { source: source, tech: techName }; } }; // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources // to select from them based on their priority. if (this.options_.sourceOrder) { // Source-first ordering foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder)); } else { // Tech-first ordering foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder); } return foundSourceAndTech || false; }; /** * The source function updates the video source * There are three types of variables you can pass as the argument. * **URL String**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * ```js * myPlayer.src("http://www.example.com/path/to/video.mp4"); * ``` * **Source Object (or element):* * A javascript object containing information * about the source file. Use this method if you want the player to determine if * it can support the file using the type information. * ```js * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); * ``` * **Array of Source Objects:* * To provide multiple versions of the source so * that it can be played using HTML5 across browsers you can use an array of * source objects. Video.js will detect which version is supported and load that * file. * ```js * myPlayer.src([ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } * ]); * ``` * * @param {String|Object|Array=} source The source URL, object, or array of sources * @return {String} The current video source when getting * @return {String} The player when setting * @method src */ Player.prototype.src = function src(source) { if (source === undefined) { return this.techGet_('src'); } var currentTech = _techTechJs2['default'].getTech(this.techName_); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!currentTech) { currentTech = _componentJs2['default'].getComponent(this.techName_); } // case: Array of source objects to choose from and pick the best to play if (Array.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !currentTech.canPlaySource(source)) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function () { // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (currentTech.prototype.hasOwnProperty('setSource')) { this.techCall_('setSource', source); } else { this.techCall_('src', source.src); } if (this.options_.preload === 'auto') { this.load(); } if (this.options_.autoplay) { this.play(); } // Set the source synchronously if possible (#2326) }, true); } } return this; }; /** * Handle an array of source objects * * @param {Array} sources Array of source objects * @private * @method sourceList_ */ Player.prototype.sourceList_ = function sourceList_(sources) { var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName_) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech_(sourceTech.tech, sourceTech.source); } } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * * @return {Player} Returns the player * @method load */ Player.prototype.load = function load() { this.techCall_('load'); return this; }; /** * Reset the player. Loads the first tech in the techOrder, * and calls `reset` on the tech`. * * @return {Player} Returns the player * @method reset */ Player.prototype.reset = function reset() { this.loadTech_(_utilsToTitleCaseJs2['default'](this.options_.techOrder[0]), null); this.techCall_('reset'); return this; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * * @return {String} The current source * @method currentSrc */ Player.prototype.currentSrc = function currentSrc() { return this.techGet_('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * * @return {String} The source MIME type * @method currentType */ Player.prototype.currentType = function currentType() { return this.currentType_ || ''; }; /** * Get or set the preload attribute * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The preload attribute value when getting * @return {Player} Returns the player when setting * @method preload */ Player.prototype.preload = function preload(value) { if (value !== undefined) { this.techCall_('setPreload', value); this.options_.preload = value; return this; } return this.techGet_('preload'); }; /** * Get or set the autoplay attribute. * * @param {Boolean} value Boolean to determine if video should autoplay * @return {String} The autoplay attribute value when getting * @return {Player} Returns the player when setting * @method autoplay */ Player.prototype.autoplay = function autoplay(value) { if (value !== undefined) { this.techCall_('setAutoplay', value); this.options_.autoplay = value; return this; } return this.techGet_('autoplay', value); }; /** * Get or set the loop attribute on the video element. * * @param {Boolean} value Boolean to determine if video should loop * @return {String} The loop attribute value when getting * @return {Player} Returns the player when setting * @method loop */ Player.prototype.loop = function loop(value) { if (value !== undefined) { this.techCall_('setLoop', value); this.options_['loop'] = value; return this; } return this.techGet_('loop'); }; /** * Get or set the poster image source url * * ##### EXAMPLE: * ```js * // get * var currentPoster = myPlayer.poster(); * // set * myPlayer.poster('http://example.com/myImage.jpg'); * ``` * * @param {String=} src Poster image source URL * @return {String} poster URL when getting * @return {Player} self when setting * @method poster */ Player.prototype.poster = function poster(src) { if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall_('setPoster', src); // alert components that the poster has been set this.trigger('posterchange'); return this; }; /** * Some techs (e.g. YouTube) can provide a poster source in an * asynchronous way. We want the poster component to use this * poster source so that it covers up the tech's controls. * (YouTube's play button). However we only want to use this * soruce if the player user hasn't set a poster through * the normal APIs. * * @private * @method handleTechPosterChange_ */ Player.prototype.handleTechPosterChange_ = function handleTechPosterChange_() { if (!this.poster_ && this.tech_ && this.tech_.poster) { this.poster_ = this.tech_.poster() || ''; // Let components know the poster has changed this.trigger('posterchange'); } }; /** * Get or set whether or not the controls are showing. * * @param {Boolean} bool Set controls to showing or not * @return {Boolean} Controls are showing * @method controls */ Player.prototype.controls = function controls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (this.usingNativeControls()) { this.techCall_('setControls', bool); } if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); if (!this.usingNativeControls()) { this.addTechControlsListeners_(); } } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); if (!this.usingNativeControls()) { this.removeTechControlsListeners_(); } } } return this; } return !!this.controls_; }; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @param {Boolean} bool True signals that native controls are on * @return {Player} Returns the player * @private * @method usingNativeControls */ Player.prototype.usingNativeControls = function usingNativeControls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event usingnativecontrols * @memberof Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return !!this.usingNativeControls_; }; /** * Set or get the current MediaError * * @param {*} err A MediaError or a String/Number to be turned into a MediaError * @return {MediaError|null} when getting * @return {Player} when setting * @method error */ Player.prototype.error = function error(err) { if (err === undefined) { return this.error_ || null; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); this.errorDisplay.close(); return this; } // error instance if (err instanceof _mediaErrorJs2['default']) { this.error_ = err; } else { this.error_ = new _mediaErrorJs2['default'](err); } // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object _utilsLogJs2['default'].error('(CODE:' + this.error_.code + ' ' + _mediaErrorJs2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_); // fire an error event on the player this.trigger('error'); return this; }; /** * Returns whether or not the player is in the "ended" state. * * @return {Boolean} True if the player is in the ended state, false if not. * @method ended */ Player.prototype.ended = function ended() { return this.techGet_('ended'); }; /** * Returns whether or not the player is in the "seeking" state. * * @return {Boolean} True if the player is in the seeking state, false if not. * @method seeking */ Player.prototype.seeking = function seeking() { return this.techGet_('seeking'); }; /** * Returns the TimeRanges of the media that are currently available * for seeking to. * * @return {TimeRanges} the seekable intervals of the media timeline * @method seekable */ Player.prototype.seekable = function seekable() { return this.techGet_('seekable'); }; /** * Report user activity * * @param {Object} event Event object * @method reportUserActivity */ Player.prototype.reportUserActivity = function reportUserActivity(event) { this.userActivity_ = true; }; /** * Get/set if user is active * * @param {Boolean} bool Value when setting * @return {Boolean} Value if user is active user when getting * @method userActive */ Player.prototype.userActive = function userActive(bool) { if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if (this.tech_) { this.tech_.one('mousemove', function (e) { e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); this.trigger('userinactive'); } } return this; } return this.userActive_; }; /** * Listen for user activity based on timeout value * * @private * @method listenForUserActivity_ */ Player.prototype.listenForUserActivity_ = function listenForUserActivity_() { var mouseInProgress = undefined, lastMoveX = undefined, lastMoveY = undefined; var handleActivity = Fn.bind(this, this.reportUserActivity); var handleMouseMove = function handleMouseMove(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; handleActivity(); } }; var handleMouseDown = function handleMouseDown() { handleActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(handleActivity, 250); }; var handleMouseUp = function handleMouseUp(event) { handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', handleMouseDown); this.on('mousemove', handleMouseMove); this.on('mouseup', handleMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', handleActivity); this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ var inactivityTimeout = undefined; var activityCheck = this.setInterval(function () { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options_['inactivityTimeout']; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activityCheck loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. A playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed * playback, for instance. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate * * @param {Number} rate New playback rate to set. * @return {Number} Returns the new playback rate when setting * @return {Number} Returns the current playback rate when getting * @method playbackRate */ Player.prototype.playbackRate = function playbackRate(rate) { if (rate !== undefined) { this.techCall_('setPlaybackRate', rate); return this; } if (this.tech_ && this.tech_['featuresPlaybackRate']) { return this.techGet_('playbackRate'); } else { return 1.0; } }; /** * Gets or sets the audio flag * * @param {Boolean} bool True signals that this is an audio player. * @return {Boolean} Returns true if player is audio, false if not when getting * @return {Player} Returns the player if setting * @private * @method isAudio */ Player.prototype.isAudio = function isAudio(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return !!this.isAudio_; }; /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states * @return {Number} the current network activity state * @method networkState */ Player.prototype.networkState = function networkState() { return this.techGet_('networkState'); }; /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate * @return {Number} the current playback rendering state * @method readyState */ Player.prototype.readyState = function readyState() { return this.techGet_('readyState'); }; /* * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impaired * Subtitles - text displayed over the video for those who don't understand language in the video * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device */ /** * Get an array of associated text tracks. captions, subtitles, chapters, descriptions * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * * @return {Array} Array of track objects * @method textTracks */ Player.prototype.textTracks = function textTracks() { // cannot use techGet_ directly because it checks to see whether the tech is ready. // Flash is unlikely to be ready in time but textTracks should still work. return this.tech_ && this.tech_['textTracks'](); }; /** * Get an array of remote text tracks * * @return {Array} * @method remoteTextTracks */ Player.prototype.remoteTextTracks = function remoteTextTracks() { return this.tech_ && this.tech_['remoteTextTracks'](); }; /** * Get an array of remote html track elements * * @return {HTMLTrackElement[]} * @method remoteTextTrackEls */ Player.prototype.remoteTextTrackEls = function remoteTextTrackEls() { return this.tech_ && this.tech_['remoteTextTrackEls'](); }; /** * Add a text track * In addition to the W3C settings we allow adding additional info through options. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata * @param {String=} label Optional label * @param {String=} language Optional language * @method addTextTrack */ Player.prototype.addTextTrack = function addTextTrack(kind, label, language) { return this.tech_ && this.tech_['addTextTrack'](kind, label, language); }; /** * Add a remote text track * * @param {Object} options Options for remote text track * @method addRemoteTextTrack */ Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { return this.tech_ && this.tech_['addRemoteTextTrack'](options); }; /** * Remove a remote text track * * @param {Object} track Remote text track to remove * @method removeRemoteTextTrack */ Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.tech_ && this.tech_['removeRemoteTextTrack'](track); }; /** * Get video width * * @return {Number} Video width * @method videoWidth */ Player.prototype.videoWidth = function videoWidth() { return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0; }; /** * Get video height * * @return {Number} Video height * @method videoHeight */ Player.prototype.videoHeight = function videoHeight() { return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0; }; // Methods to add support for // initialTime: function(){ return this.techCall_('initialTime'); }, // startOffsetTime: function(){ return this.techCall_('startOffsetTime'); }, // played: function(){ return this.techCall_('played'); }, // videoTracks: function(){ return this.techCall_('videoTracks'); }, // audioTracks: function(){ return this.techCall_('audioTracks'); }, // defaultPlaybackRate: function(){ return this.techCall_('defaultPlaybackRate'); }, // defaultMuted: function(){ return this.techCall_('defaultMuted'); } /** * The player's language code * NOTE: The language should be set in the player options if you want the * the controls to be built with a specific language. Changing the lanugage * later will not update controls text. * * @param {String} code The locale string * @return {String} The locale string when getting * @return {Player} self when setting * @method language */ Player.prototype.language = function language(code) { if (code === undefined) { return this.language_; } this.language_ = ('' + code).toLowerCase(); return this; }; /** * Get the player's language dictionary * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time * Languages specified directly in the player options have precedence * * @return {Array} Array of languages * @method languages */ Player.prototype.languages = function languages() { return _utilsMergeOptionsJs2['default'](Player.prototype.options_.languages, this.languages_); }; /** * Converts track info to JSON * * @return {Object} JSON object of options * @method toJSON */ Player.prototype.toJSON = function toJSON() { var options = _utilsMergeOptionsJs2['default'](this.options_); var tracks = options.tracks; options.tracks = []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // deep merge tracks and null out player so no circular references track = _utilsMergeOptionsJs2['default'](track); track.player = undefined; options.tracks[i] = track; } return options; }; /** * Creates a simple modal dialog (an instance of the `ModalDialog` * component) that immediately overlays the player with arbitrary * content and removes itself when closed. * * @param {String|Function|Element|Array|Null} content * Same as `ModalDialog#content`'s param of the same name. * * The most straight-forward usage is to provide a string or DOM * element. * * @param {Object} [options] * Extra options which will be passed on to the `ModalDialog`. * * @return {ModalDialog} */ Player.prototype.createModal = function createModal(content, options) { var player = this; options = options || {}; options.content = content || ''; var modal = new _modalDialog2['default'](player, options); player.addChild(modal); modal.on('dispose', function () { player.removeChild(modal); }); return modal.open(); }; /** * Gets tag settings * * @param {Element} tag The player tag * @return {Array} An array of sources and track objects * @static * @method getTagSettings */ Player.getTagSettings = function getTagSettings(tag) { var baseOptions = { 'sources': [], 'tracks': [] }; var tagOptions = Dom.getElAttributes(tag); var dataSetup = tagOptions['data-setup']; // Check if data-setup attr exists. if (dataSetup !== null) { // Parse options JSON var _safeParseTuple = _safeJsonParseTuple2['default'](dataSetup || '{}'); var err = _safeParseTuple[0]; var data = _safeParseTuple[1]; if (err) { _utilsLogJs2['default'].error(err); } _objectAssign2['default'](tagOptions, data); } _objectAssign2['default'](baseOptions, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children = tag.childNodes; for (var i = 0, j = children.length; i < j; i++) { var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ var childName = child.nodeName.toLowerCase(); if (childName === 'source') { baseOptions.sources.push(Dom.getElAttributes(child)); } else if (childName === 'track') { baseOptions.tracks.push(Dom.getElAttributes(child)); } } } return baseOptions; }; return Player; })(_componentJs2['default']); Player.players = {}; var navigator = _globalWindow2['default'].navigator; /* * Player instance options, surfaced using options * options = Player.prototype.options_ * Make changes in options, not here. * * @type {Object} * @private */ Player.prototype.options_ = { // Default order of fallback technology techOrder: ['html5', 'flash'], // techOrder: ['flash','html5'], html5: {}, flash: {}, // defaultVolume: 0.85, defaultVolume: 0.00, // The freakin seaguls are driving me crazy! // default inactivity timeout inactivityTimeout: 2000, // default playback rates playbackRates: [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // Included control sets children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'controlBar', 'errorDisplay', 'textTrackSettings'], language: _globalDocument2['default'].getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en', // locales and their language translations languages: {}, // Default message to show when a video cannot be played. notSupportedMessage: 'No compatible source was found for this video.' }; /** * Fired when the player has initial duration and dimension information * * @event loadedmetadata */ Player.prototype.handleLoadedMetaData_; /** * Fired when the player has downloaded data at the current playback position * * @event loadeddata */ Player.prototype.handleLoadedData_; /** * Fired when the user is active, e.g. moves the mouse over the player * * @event useractive */ Player.prototype.handleUserActive_; /** * Fired when the user is inactive, e.g. a short delay after the last mouse move or control interaction * * @event userinactive */ Player.prototype.handleUserInactive_; /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * * @event timeupdate */ Player.prototype.handleTimeUpdate_; /** * Fired when video playback ends * * @event ended */ Player.prototype.handleTechEnded_; /** * Fired when the volume changes * * @event volumechange */ Player.prototype.handleVolumeChange_; /** * Fired when an error occurs * * @event error */ Player.prototype.handleError_; Player.prototype.flexNotSupported_ = function () { var elem = _globalDocument2['default'].createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more // common flex features that we can rely on when checking for flex support. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || 'msFlexOrder' in elem.style) /* IE10-specific (2012 flex spec) */; }; _componentJs2['default'].registerComponent('Player', Player); exports['default'] = Player; module.exports = exports['default']; // If empty string, make it a parsable json object. },{"./big-play-button.js":63,"./component.js":67,"./control-bar/control-bar.js":68,"./error-display.js":98,"./fullscreen-api.js":101,"./loading-spinner.js":102,"./media-error.js":103,"./modal-dialog":107,"./poster-image.js":112,"./tech/html5.js":117,"./tech/loader.js":118,"./tech/tech.js":119,"./tracks/text-track-display.js":123,"./tracks/text-track-list-converter.js":125,"./tracks/text-track-settings.js":127,"./utils/browser.js":129,"./utils/buffer.js":130,"./utils/dom.js":132,"./utils/events.js":133,"./utils/fn.js":134,"./utils/guid.js":136,"./utils/log.js":137,"./utils/merge-options.js":138,"./utils/stylesheet.js":139,"./utils/time-ranges.js":140,"./utils/to-title-case.js":141,"global/document":1,"global/window":2,"object.assign":45,"safe-json-parse/tuple":54}],109:[function(_dereq_,module,exports){ /** * @file plugins.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _playerJs = _dereq_('./player.js'); var _playerJs2 = _interopRequireDefault(_playerJs); /** * The method for registering a video.js plugin * * @param {String} name The name of the plugin * @param {Function} init The function that is run when the player inits * @method plugin */ var plugin = function plugin(name, init) { _playerJs2['default'].prototype[name] = init; }; exports['default'] = plugin; module.exports = exports['default']; },{"./player.js":108}],110:[function(_dereq_,module,exports){ /** * @file popup-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _clickableComponentJs = _dereq_('../clickable-component.js'); var _clickableComponentJs2 = _interopRequireDefault(_clickableComponentJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _popupJs = _dereq_('./popup.js'); var _popupJs2 = _interopRequireDefault(_popupJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); /** * A button class with a popup control * * @param {Player|Object} player * @param {Object=} options * @extends ClickableComponent * @class PopupButton */ var PopupButton = (function (_ClickableComponent) { _inherits(PopupButton, _ClickableComponent); function PopupButton(player) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, PopupButton); _ClickableComponent.call(this, player, options); this.update(); } /** * Update popup * * @method update */ PopupButton.prototype.update = function update() { var popup = this.createPopup(); if (this.popup) { this.removeChild(this.popup); } this.popup = popup; this.addChild(popup); if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Create popup - Override with specific functionality for component * * @return {Popup} The constructed popup * @method createPopup */ PopupButton.prototype.createPopup = function createPopup() {}; /** * Create the component's DOM element * * @return {Element} * @method createEl */ PopupButton.prototype.createEl = function createEl() { return _ClickableComponent.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PopupButton.prototype.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return 'vjs-menu-button ' + menuButtonClass + ' ' + _ClickableComponent.prototype.buildCSSClass.call(this); }; return PopupButton; })(_clickableComponentJs2['default']); _componentJs2['default'].registerComponent('PopupButton', PopupButton); exports['default'] = PopupButton; module.exports = exports['default']; },{"../clickable-component.js":65,"../component.js":67,"../utils/dom.js":132,"../utils/fn.js":134,"../utils/to-title-case.js":141,"./popup.js":111}],111:[function(_dereq_,module,exports){ /** * @file popup.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsEventsJs = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); /** * The Popup component is used to build pop up controls. * * @extends Component * @class Popup */ var Popup = (function (_Component) { _inherits(Popup, _Component); function Popup() { _classCallCheck(this, Popup); _Component.apply(this, arguments); } /** * Add a popup item to the popup * * @param {Object|String} component Component or component type to add * @method addItem */ Popup.prototype.addItem = function addItem(component) { this.addChild(component); component.on('click', Fn.bind(this, function () { this.unlockShowing(); })); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Popup.prototype.createEl = function createEl() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = Dom.createEl(contentElType, { className: 'vjs-menu-content' }); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Popup Buttons, // where a click on the parent is significant Events.on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; return Popup; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Popup', Popup); exports['default'] = Popup; module.exports = exports['default']; },{"../component.js":67,"../utils/dom.js":132,"../utils/events.js":133,"../utils/fn.js":134}],112:[function(_dereq_,module,exports){ /** * @file poster-image.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _clickableComponentJs = _dereq_('./clickable-component.js'); var _clickableComponentJs2 = _interopRequireDefault(_clickableComponentJs); var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); /** * The component that handles showing the poster image. * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PosterImage */ var PosterImage = (function (_ClickableComponent) { _inherits(PosterImage, _ClickableComponent); function PosterImage(player, options) { _classCallCheck(this, PosterImage); _ClickableComponent.call(this, player, options); this.update(); player.on('posterchange', Fn.bind(this, this.update)); } /** * Clean up the poster image * * @method dispose */ PosterImage.prototype.dispose = function dispose() { this.player().off('posterchange', this.update); _ClickableComponent.prototype.dispose.call(this); }; /** * Create the poster's image element * * @return {Element} * @method createEl */ PosterImage.prototype.createEl = function createEl() { var el = Dom.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!browser.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = Dom.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * Event handler for updates to the player's poster source * * @method update */ PosterImage.prototype.update = function update() { var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } }; /** * Set the poster source depending on the display method * * @param {String} url The URL to the poster source * @method setSrc */ PosterImage.prototype.setSrc = function setSrc(url) { if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { var backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * Event handler for clicks on the poster image * * @method handleClick */ PosterImage.prototype.handleClick = function handleClick() { // We don't want a click to trigger playback when controls are disabled // but CSS should be hiding the poster to prevent that from happening if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; return PosterImage; })(_clickableComponentJs2['default']); _componentJs2['default'].registerComponent('PosterImage', PosterImage); exports['default'] = PosterImage; module.exports = exports['default']; },{"./clickable-component.js":65,"./component.js":67,"./utils/browser.js":129,"./utils/dom.js":132,"./utils/fn.js":134}],113:[function(_dereq_,module,exports){ /** * @file setup.js * * Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } 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; } } var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _windowLoaded = false; var videojs = undefined; // Automatically set up any tags that have a data-setup attribute var autoSetup = function autoSetup() { // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements // to build up a new, combined list of elements. var vids = _globalDocument2['default'].getElementsByTagName('video'); var audios = _globalDocument2['default'].getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for (var i = 0, e = vids.length; i < e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for (var i = 0, e = audios.length; i < e; i++) { mediaEls.push(audios[i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var i = 0, e = mediaEls.length; i < e; i++) { var mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl['player'] === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. var player = videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }; // Pause to let the DOM keep processing var autoSetupTimeout = function autoSetupTimeout(wait, vjs) { videojs = vjs; setTimeout(autoSetup, wait); }; if (_globalDocument2['default'].readyState === 'complete') { _windowLoaded = true; } else { Events.one(_globalWindow2['default'], 'load', function () { _windowLoaded = true; }); } var hasLoaded = function hasLoaded() { return _windowLoaded; }; exports.autoSetup = autoSetup; exports.autoSetupTimeout = autoSetupTimeout; exports.hasLoaded = hasLoaded; },{"./utils/events.js":133,"global/document":1,"global/window":2}],114:[function(_dereq_,module,exports){ /** * @file slider.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * The base functionality for sliders like the volume bar and seek bar * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class Slider */ var Slider = (function (_Component) { _inherits(Slider, _Component); function Slider(player, options) { _classCallCheck(this, Slider); _Component.call(this, player, options); // Set property names to bar to match with the child Slider class is looking for this.bar = this.getChild(this.options_.barName); // Set a horizontal or vertical class on the slider depending on the slider type this.vertical(!!this.options_.vertical); this.on('mousedown', this.handleMouseDown); this.on('touchstart', this.handleMouseDown); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); this.on('click', this.handleClick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerEvent, this.update); } /** * Create the component's DOM element * * @param {String} type Type of element to create * @param {Object=} props List of properties in Object form * @return {Element} * @method createEl */ Slider.prototype.createEl = function createEl(type) { var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = _objectAssign2['default']({ tabIndex: 0 }, props); attributes = _objectAssign2['default']({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, attributes); return _Component.prototype.createEl.call(this, type, props, attributes); }; /** * Handle mouse down on slider * * @param {Object} event Mouse down event object * @method handleMouseDown */ Slider.prototype.handleMouseDown = function handleMouseDown(event) { event.preventDefault(); Dom.blockTextSelection(); this.addClass('vjs-sliding'); this.trigger('slideractive'); this.on(_globalDocument2['default'], 'mousemove', this.handleMouseMove); this.on(_globalDocument2['default'], 'mouseup', this.handleMouseUp); this.on(_globalDocument2['default'], 'touchmove', this.handleMouseMove); this.on(_globalDocument2['default'], 'touchend', this.handleMouseUp); this.handleMouseMove(event); }; /** * To be overridden by a subclass * * @method handleMouseMove */ Slider.prototype.handleMouseMove = function handleMouseMove() {}; /** * Handle mouse up on Slider * * @method handleMouseUp */ Slider.prototype.handleMouseUp = function handleMouseUp() { Dom.unblockTextSelection(); this.removeClass('vjs-sliding'); this.trigger('sliderinactive'); this.off(_globalDocument2['default'], 'mousemove', this.handleMouseMove); this.off(_globalDocument2['default'], 'mouseup', this.handleMouseUp); this.off(_globalDocument2['default'], 'touchmove', this.handleMouseMove); this.off(_globalDocument2['default'], 'touchend', this.handleMouseUp); this.update(); }; /** * Update slider * * @method update */ Slider.prototype.update = function update() { // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) return; // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing()) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var progress = this.getPercent(); var bar = this.bar; // If there's no bar... if (!bar) return; // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } // Convert to a percentage for setting var percentage = (progress * 100).toFixed(2) + '%'; // Set the new bar width or height if (this.vertical()) { bar.el().style.height = percentage; } else { bar.el().style.width = percentage; } }; /** * Calculate distance for slider * * @param {Object} event Event object * @method calculateDistance */ Slider.prototype.calculateDistance = function calculateDistance(event) { var position = Dom.getPointerPosition(this.el_, event); if (this.vertical()) { return position.y; } return position.x; }; /** * Handle on focus for slider * * @method handleFocus */ Slider.prototype.handleFocus = function handleFocus() { this.on(_globalDocument2['default'], 'keydown', this.handleKeyPress); }; /** * Handle key press for slider * * @param {Object} event Event object * @method handleKeyPress */ Slider.prototype.handleKeyPress = function handleKeyPress(event) { if (event.which === 37 || event.which === 40) { // Left and Down Arrows event.preventDefault(); this.stepBack(); } else if (event.which === 38 || event.which === 39) { // Up and Right Arrows event.preventDefault(); this.stepForward(); } }; /** * Handle on blur for slider * * @method handleBlur */ Slider.prototype.handleBlur = function handleBlur() { this.off(_globalDocument2['default'], 'keydown', this.handleKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * * @param {Object} event Event object * @method handleClick */ Slider.prototype.handleClick = function handleClick(event) { event.stopImmediatePropagation(); event.preventDefault(); }; /** * Get/set if slider is horizontal for vertical * * @param {Boolean} bool True if slider is vertical, false is horizontal * @return {Boolean} True if slider is vertical, false is horizontal * @method vertical */ Slider.prototype.vertical = function vertical(bool) { if (bool === undefined) { return this.vertical_ || false; } this.vertical_ = !!bool; if (this.vertical_) { this.addClass('vjs-slider-vertical'); } else { this.addClass('vjs-slider-horizontal'); } return this; }; return Slider; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Slider', Slider); exports['default'] = Slider; module.exports = exports['default']; },{"../component.js":67,"../utils/dom.js":132,"global/document":1,"object.assign":45}],115:[function(_dereq_,module,exports){ /** * @file flash-rtmp.js */ 'use strict'; exports.__esModule = true; function FlashRtmpDecorator(Flash) { Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; Flash.streamFromParts = function (connection, stream) { return connection + '&' + stream; }; Flash.streamToParts = function (src) { var parts = { connection: '', stream: '' }; if (!src) return parts; // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.search(/&(?!\w+=)/); var streamBegin = undefined; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; Flash.isStreamingType = function (srcType) { return srcType in Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid Flash.RTMP_RE = /^rtmp[set]?:\/\//i; Flash.isStreamingSrc = function (src) { return Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ Flash.rtmpSourceHandler = {}; /** * Check if Flash can play the given videotype * @param {String} type The mimetype to check * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canPlayType = function (type) { if (Flash.isStreamingType(type)) { return 'maybe'; } return ''; }; /** * Check if Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canHandleSource = function (source) { var can = Flash.rtmpSourceHandler.canPlayType(source.type); if (can) { return can; } if (Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.rtmpSourceHandler.handleSource = function (source, tech) { var srcParts = Flash.streamToParts(source.src); tech['setRtmpConnection'](srcParts.connection); tech['setRtmpStream'](srcParts.stream); }; // Register the native source handler Flash.registerSourceHandler(Flash.rtmpSourceHandler); return Flash; } exports['default'] = FlashRtmpDecorator; module.exports = exports['default']; },{}],116:[function(_dereq_,module,exports){ /** * @file flash.js * VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _tech = _dereq_('./tech'); var _tech2 = _interopRequireDefault(_tech); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsUrlJs = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js'); var _flashRtmp = _dereq_('./flash-rtmp'); var _flashRtmp2 = _interopRequireDefault(_flashRtmp); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var navigator = _globalWindow2['default'].navigator; /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Flash */ var Flash = (function (_Tech) { _inherits(Flash, _Tech); function Flash(options, ready) { _classCallCheck(this, Flash); _Tech.call(this, options, ready); // Set the source when ready if (options.source) { this.ready(function () { this.setSource(options.source); }, true); } // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options.startTime) { this.ready(function () { this.load(); this.play(); this.currentTime(options.startTime); }, true); } // Add global window functions that the swf expects // A 4.x workflow we weren't able to solve for in 5.0 // because of the need to hard code these functions // into the swf for security reasons _globalWindow2['default'].videojs = _globalWindow2['default'].videojs || {}; _globalWindow2['default'].videojs.Flash = _globalWindow2['default'].videojs.Flash || {}; _globalWindow2['default'].videojs.Flash.onReady = Flash.onReady; _globalWindow2['default'].videojs.Flash.onEvent = Flash.onEvent; _globalWindow2['default'].videojs.Flash.onError = Flash.onError; this.on('seeked', function () { this.lastSeekTarget_ = undefined; }); } // Create setters and getters for attributes /** * Create the component's DOM element * * @return {Element} * @method createEl */ Flash.prototype.createEl = function createEl() { var options = this.options_; // If video.js is hosted locally you should also set the location // for the hosted swf, which should be relative to the page (not video.js) // Otherwise this adds a CDN url. // The CDN also auto-adds a swf URL for that specific version. if (!options.swf) { options.swf = '//vjs.zencdn.net/swf/5.0.1/video-js.swf'; } // Generate ID for swf object var objId = options.techId; // Merge default flashvars with ones passed in to init var flashVars = _objectAssign2['default']({ // SWF Callback Functions 'readyFunction': 'videojs.Flash.onReady', 'eventProxyFunction': 'videojs.Flash.onEvent', 'errorEventProxyFunction': 'videojs.Flash.onError', // Player Settings 'autoplay': options.autoplay, 'preload': options.preload, 'loop': options.loop, 'muted': options.muted }, options.flashVars); // Merge default parames with ones passed in var params = _objectAssign2['default']({ 'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance 'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading }, options.params); // Merge default attributes with ones passed in var attributes = _objectAssign2['default']({ 'id': objId, 'name': objId, // Both ID and Name needed or swf to identify itself 'class': 'vjs-tech' }, options.attributes); this.el_ = Flash.embed(options.swf, flashVars, params, attributes); this.el_.tech = this; return this.el_; }; /** * Play for flash tech * * @method play */ Flash.prototype.play = function play() { if (this.ended()) { this.setCurrentTime(0); } this.el_.vjs_play(); }; /** * Pause for flash tech * * @method pause */ Flash.prototype.pause = function pause() { this.el_.vjs_pause(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Flash.prototype.src = function src(_src) { if (_src === undefined) { return this.currentSrc(); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(_src); }; /** * Set video * * @param {Object=} src Source object * @deprecated * @method setSrc */ Flash.prototype.setSrc = function setSrc(src) { // Make sure source URL is absolute. src = Url.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.autoplay()) { var tech = this; this.setTimeout(function () { tech.play(); }, 0); } }; /** * Returns true if the tech is currently seeking. * @return {boolean} true if seeking */ Flash.prototype.seeking = function seeking() { return this.lastSeekTarget_ !== undefined; }; /** * Set current time * * @param {Number} time Current time of video * @method setCurrentTime */ Flash.prototype.setCurrentTime = function setCurrentTime(time) { var seekable = this.seekable(); if (seekable.length) { // clamp to the current seekable range time = time > seekable.start(0) ? time : seekable.start(0); time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1); this.lastSeekTarget_ = time; this.trigger('seeking'); this.el_.vjs_setProperty('currentTime', time); _Tech.prototype.setCurrentTime.call(this); } }; /** * Get current time * * @param {Number=} time Current time of video * @return {Number} Current time * @method currentTime */ Flash.prototype.currentTime = function currentTime(time) { // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; /** * Get current source * * @method currentSrc */ Flash.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } else { return this.el_.vjs_getProperty('currentSrc'); } }; /** * Load media into player * * @method load */ Flash.prototype.load = function load() { this.el_.vjs_load(); }; /** * Get poster * * @method poster */ Flash.prototype.poster = function poster() { this.el_.vjs_getProperty('poster'); }; /** * Poster images are not handled by the Flash tech so make this a no-op * * @method setPoster */ Flash.prototype.setPoster = function setPoster() {}; /** * Determine if can seek in media * * @return {TimeRangeObject} * @method seekable */ Flash.prototype.seekable = function seekable() { var duration = this.duration(); if (duration === 0) { return _utilsTimeRangesJs.createTimeRange(); } return _utilsTimeRangesJs.createTimeRange(0, duration); }; /** * Get buffered time range * * @return {TimeRangeObject} * @method buffered */ Flash.prototype.buffered = function buffered() { var ranges = this.el_.vjs_getProperty('buffered'); if (ranges.length === 0) { return _utilsTimeRangesJs.createTimeRange(); } return _utilsTimeRangesJs.createTimeRange(ranges[0][0], ranges[0][1]); }; /** * Get fullscreen support - * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method supportsFullScreen */ Flash.prototype.supportsFullScreen = function supportsFullScreen() { return false; // Flash does not allow fullscreen through javascript }; /** * Request to enter fullscreen * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method enterFullScreen */ Flash.prototype.enterFullScreen = function enterFullScreen() { return false; }; return Flash; })(_tech2['default']); var _api = Flash.prototype; var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','); var _readOnly = 'networkState,readyState,initialTime,duration,startOffsetTime,paused,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(','); function _createSetter(attr) { var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); _api['set' + attrUpper] = function (val) { return this.el_.vjs_setProperty(attr, val); }; } function _createGetter(attr) { _api[attr] = function () { return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (var i = 0; i < _readWrite.length; i++) { _createGetter(_readWrite[i]); _createSetter(_readWrite[i]); } // Create getters for read-only attributes for (var i = 0; i < _readOnly.length; i++) { _createGetter(_readOnly[i]); } /* Flash Support Testing -------------------------------------------------------- */ Flash.isSupported = function () { return Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech _tech2['default'].withSourceHandlers(Flash); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler = {}; /** * Check if Flash can play the given videotype * @param {String} type The mimetype to check * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.nativeSourceHandler.canPlayType = function (type) { if (type in Flash.formats) { return 'maybe'; } return ''; }; /* * Check Flash can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.nativeSourceHandler.canHandleSource = function (source) { var type; function guessMimeType(src) { var ext = Url.getFileExtension(src); if (ext) { return 'video/' + ext; } return ''; } if (!source.type) { type = guessMimeType(source.src); } else { // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/, '').toLowerCase(); } return Flash.nativeSourceHandler.canPlayType(type); }; /* * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Flash.nativeSourceHandler.dispose = function () {}; // Register the native source handler Flash.registerSourceHandler(Flash.nativeSourceHandler); Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; Flash.onReady = function (currSwf) { var el = Dom.getEl(currSwf); var tech = el && el.tech; // if there is no el then the tech has been disposed // and the tech element was removed from the player div if (tech && tech.el()) { // check that the flash object is really ready Flash.checkReady(tech); } }; // The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object. // If it's not ready, we set a timeout to check again shortly. Flash.checkReady = function (tech) { // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function () { Flash['checkReady'](tech); }, 50); } }; // Trigger events from the swf on the player Flash.onEvent = function (swfID, eventName) { var tech = Dom.getEl(swfID).tech; tech.trigger(eventName); }; // Log errors from the swf Flash.onError = function (swfID, err) { var tech = Dom.getEl(swfID).tech; // trigger MEDIA_ERR_SRC_NOT_SUPPORTED if (err === 'srcnotfound') { return tech.error(4); } // trigger a custom error tech.error('FLASH: ' + err); }; // Flash Version Check Flash.version = function () { var version = '0,0,0'; // IE try { version = new _globalWindow2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch (e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) { version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch (err) {} } return version.split(','); }; // Flash embedding method. Only used in non-iframe mode Flash.embed = function (swf, flashVars, params, attributes) { var code = Flash.getEmbedCode(swf, flashVars, params, attributes); // Get element by embedding code and retrieving created element var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0]; return obj; }; Flash.getEmbedCode = function (swf, flashVars, params, attributes) { var objTag = '<object type="application/x-shockwave-flash" '; var flashVarsString = ''; var paramsString = ''; var attrsString = ''; // Convert flash vars to string if (flashVars) { Object.getOwnPropertyNames(flashVars).forEach(function (key) { flashVarsString += key + '=' + flashVars[key] + '&amp;'; }); } // Add swf, flashVars, and other default params params = _objectAssign2['default']({ 'movie': swf, 'flashvars': flashVarsString, 'allowScriptAccess': 'always', // Required to talk to swf 'allowNetworking': 'all' // All should be default, but having security issues. }, params); // Create param tags string Object.getOwnPropertyNames(params).forEach(function (key) { paramsString += '<param name="' + key + '" value="' + params[key] + '" />'; }); attributes = _objectAssign2['default']({ // Add swf to attributes (need both for IE and Others to work) 'data': swf, // Default to 100% width/height 'width': '100%', 'height': '100%' }, attributes); // Create Attributes string Object.getOwnPropertyNames(attributes).forEach(function (key) { attrsString += key + '="' + attributes[key] + '" '; }); return '' + objTag + attrsString + '>' + paramsString + '</object>'; }; // Run Flash through the RTMP decorator _flashRtmp2['default'](Flash); _component2['default'].registerComponent('Flash', Flash); _tech2['default'].registerTech('Flash', Flash); exports['default'] = Flash; module.exports = exports['default']; },{"../component":67,"../utils/dom.js":132,"../utils/time-ranges.js":140,"../utils/url.js":142,"./flash-rtmp":115,"./tech":119,"global/window":2,"object.assign":45}],117:[function(_dereq_,module,exports){ /** * @file html5.js * HTML5 Media Controller - Wrapper for HTML5 Media API */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _techJs = _dereq_('./tech.js'); var _techJs2 = _interopRequireDefault(_techJs); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsUrlJs = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('../utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); /** * HTML5 Media Controller - Wrapper for HTML5 Media API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Html5 */ var Html5 = (function (_Tech) { _inherits(Html5, _Tech); function Html5(options, ready) { _classCallCheck(this, Html5); _Tech.call(this, options, ready); var source = options.source; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) { this.setSource(source); } else { this.handleLateInit_(this.el_); } if (this.el_.hasChildNodes()) { var nodes = this.el_.childNodes; var nodesLength = nodes.length; var removeNodes = []; while (nodesLength--) { var node = nodes[nodesLength]; var nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!this.featuresNativeTextTracks) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { // store HTMLTrackElement and TextTrack to remote list this.remoteTextTrackEls().addTrackElement_(node); this.remoteTextTracks().addTrack_(node.track); } } } for (var i = 0; i < removeNodes.length; i++) { this.el_.removeChild(removeNodes[i]); } } if (this.featuresNativeTextTracks) { this.handleTextTrackChange_ = Fn.bind(this, this.handleTextTrackChange); this.handleTextTrackAdd_ = Fn.bind(this, this.handleTextTrackAdd); this.handleTextTrackRemove_ = Fn.bind(this, this.handleTextTrackRemove); this.proxyNativeTextTracks_(); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if (browser.TOUCH_ENABLED && options.nativeControlsForTouch === true || browser.IS_IPHONE || browser.IS_NATIVE_ANDROID) { this.setControls(true); } this.triggerReady(); } /* HTML5 Support Testing ---------------------------------------------------- */ /* * Element for testing browser HTML5 video capabilities * * @type {Element} * @constant * @private */ /** * Dispose of html5 media element * * @method dispose */ Html5.prototype.dispose = function dispose() { var tt = this.el().textTracks; var emulatedTt = this.textTracks(); // remove native event listeners if (tt && tt.removeEventListener) { tt.removeEventListener('change', this.handleTextTrackChange_); tt.removeEventListener('addtrack', this.handleTextTrackAdd_); tt.removeEventListener('removetrack', this.handleTextTrackRemove_); } // clearout the emulated text track list. var i = emulatedTt.length; while (i--) { emulatedTt.removeTrack_(emulatedTt[i]); } Html5.disposeMediaElement(this.el_); _Tech.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Html5.prototype.createEl = function createEl() { var el = this.options_.tag; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this['movingMediaElementInDOM'] === false) { // If the original tag is still there, clone and remove it. if (el) { var clone = el.cloneNode(true); el.parentNode.insertBefore(clone, el); Html5.disposeMediaElement(el); el = clone; } else { el = _globalDocument2['default'].createElement('video'); // determine if native controls should be used var tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag); var attributes = _utilsMergeOptionsJs2['default']({}, tagAttributes); if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) { delete attributes.controls; } Dom.setElAttributes(el, _objectAssign2['default'](attributes, { id: this.options_.techId, 'class': 'vjs-tech' })); } } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay', 'preload', 'loop', 'muted']; for (var i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof this.options_[attr] !== 'undefined') { overwriteAttrs[attr] = this.options_[attr]; } Dom.setElAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }; // If we're loading the playback object after it has started loading // or playing the video (often with autoplay on) then the loadstart event // has already fired and we need to fire it manually because many things // rely on it. Html5.prototype.handleLateInit_ = function handleLateInit_(el) { var _this = this; if (el.networkState === 0 || el.networkState === 3) { // The video element hasn't started loading the source yet // or didn't find a source return; } if (el.readyState === 0) { var _ret = (function () { // NetworkState is set synchronously BUT loadstart is fired at the // end of the current stack, usually before setInterval(fn, 0). // So at this point we know loadstart may have already fired or is // about to fire, and either way the player hasn't seen it yet. // We don't want to fire loadstart prematurely here and cause a // double loadstart so we'll wait and see if it happens between now // and the next loop, and fire it if not. // HOWEVER, we also want to make sure it fires before loadedmetadata // which could also happen between now and the next loop, so we'll // watch for that also. var loadstartFired = false; var setLoadstartFired = function setLoadstartFired() { loadstartFired = true; }; _this.on('loadstart', setLoadstartFired); var triggerLoadstart = function triggerLoadstart() { // We did miss the original loadstart. Make sure the player // sees loadstart before loadedmetadata if (!loadstartFired) { this.trigger('loadstart'); } }; _this.on('loadedmetadata', triggerLoadstart); _this.ready(function () { this.off('loadstart', setLoadstartFired); this.off('loadedmetadata', triggerLoadstart); if (!loadstartFired) { // We did miss the original native loadstart. Fire it now. this.trigger('loadstart'); } }); return { v: undefined }; })(); if (typeof _ret === 'object') return _ret.v; } // From here on we know that loadstart already fired and we missed it. // The other readyState events aren't as much of a problem if we double // them, so not going to go to as much trouble as loadstart to prevent // that unless we find reason to. var eventsToTrigger = ['loadstart']; // loadedmetadata: newly equal to HAVE_METADATA (1) or greater eventsToTrigger.push('loadedmetadata'); // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater if (el.readyState >= 2) { eventsToTrigger.push('loadeddata'); } // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater if (el.readyState >= 3) { eventsToTrigger.push('canplay'); } // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4) if (el.readyState >= 4) { eventsToTrigger.push('canplaythrough'); } // We still need to give the player time to add event listeners this.ready(function () { eventsToTrigger.forEach(function (type) { this.trigger(type); }, this); }); }; Html5.prototype.proxyNativeTextTracks_ = function proxyNativeTextTracks_() { var tt = this.el().textTracks; if (tt && tt.addEventListener) { tt.addEventListener('change', this.handleTextTrackChange_); tt.addEventListener('addtrack', this.handleTextTrackAdd_); tt.addEventListener('removetrack', this.handleTextTrackRemove_); } }; Html5.prototype.handleTextTrackChange = function handleTextTrackChange(e) { var tt = this.textTracks(); this.textTracks().trigger({ type: 'change', target: tt, currentTarget: tt, srcElement: tt }); }; Html5.prototype.handleTextTrackAdd = function handleTextTrackAdd(e) { this.textTracks().addTrack_(e.track); }; Html5.prototype.handleTextTrackRemove = function handleTextTrackRemove(e) { this.textTracks().removeTrack_(e.track); }; /** * Play for html5 tech * * @method play */ Html5.prototype.play = function play() { this.el_.play(); }; /** * Pause for html5 tech * * @method pause */ Html5.prototype.pause = function pause() { this.el_.pause(); }; /** * Paused for html5 tech * * @return {Boolean} * @method paused */ Html5.prototype.paused = function paused() { return this.el_.paused; }; /** * Get current time * * @return {Number} * @method currentTime */ Html5.prototype.currentTime = function currentTime() { return this.el_.currentTime; }; /** * Set current time * * @param {Number} seconds Current time of video * @method setCurrentTime */ Html5.prototype.setCurrentTime = function setCurrentTime(seconds) { try { this.el_.currentTime = seconds; } catch (e) { _utilsLogJs2['default'](e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; /** * Get duration * * @return {Number} * @method duration */ Html5.prototype.duration = function duration() { return this.el_.duration || 0; }; /** * Get a TimeRange object that represents the intersection * of the time ranges for which the user agent has all * relevant media * * @return {TimeRangeObject} * @method buffered */ Html5.prototype.buffered = function buffered() { return this.el_.buffered; }; /** * Get volume level * * @return {Number} * @method volume */ Html5.prototype.volume = function volume() { return this.el_.volume; }; /** * Set volume level * * @param {Number} percentAsDecimal Volume percent as a decimal * @method setVolume */ Html5.prototype.setVolume = function setVolume(percentAsDecimal) { this.el_.volume = percentAsDecimal; }; /** * Get if muted * * @return {Boolean} * @method muted */ Html5.prototype.muted = function muted() { return this.el_.muted; }; /** * Set muted * * @param {Boolean} If player is to be muted or note * @method setMuted */ Html5.prototype.setMuted = function setMuted(muted) { this.el_.muted = muted; }; /** * Get player width * * @return {Number} * @method width */ Html5.prototype.width = function width() { return this.el_.offsetWidth; }; /** * Get player height * * @return {Number} * @method height */ Html5.prototype.height = function height() { return this.el_.offsetHeight; }; /** * Get if there is fullscreen support * * @return {Boolean} * @method supportsFullScreen */ Html5.prototype.supportsFullScreen = function supportsFullScreen() { if (typeof this.el_.webkitEnterFullScreen === 'function') { var userAgent = _globalWindow2['default'].navigator.userAgent; // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) { return true; } } return false; }; /** * Request to enter fullscreen * * @method enterFullScreen */ Html5.prototype.enterFullScreen = function enterFullScreen() { var video = this.el_; if ('webkitDisplayingFullscreen' in video) { this.one('webkitbeginfullscreen', function () { this.one('webkitendfullscreen', function () { this.trigger('fullscreenchange', { isFullscreen: false }); }); this.trigger('fullscreenchange', { isFullscreen: true }); }); } if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function () { video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; /** * Request to exit fullscreen * * @method exitFullScreen */ Html5.prototype.exitFullScreen = function exitFullScreen() { this.el_.webkitExitFullScreen(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Html5.prototype.src = function src(_src) { if (_src === undefined) { return this.el_.src; } else { // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(_src); } }; /** * Set video * * @param {Object} src Source object * @deprecated * @method setSrc */ Html5.prototype.setSrc = function setSrc(src) { this.el_.src = src; }; /** * Load media into player * * @method load */ Html5.prototype.load = function load() { this.el_.load(); }; /** * Reset the tech. Removes all sources and calls `load`. * * @method reset */ Html5.prototype.reset = function reset() { Html5.resetMediaElement(this.el_); }; /** * Get current source * * @return {Object} * @method currentSrc */ Html5.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } else { return this.el_.currentSrc; } }; /** * Get poster * * @return {String} * @method poster */ Html5.prototype.poster = function poster() { return this.el_.poster; }; /** * Set poster * * @param {String} val URL to poster image * @method */ Html5.prototype.setPoster = function setPoster(val) { this.el_.poster = val; }; /** * Get preload attribute * * @return {String} * @method preload */ Html5.prototype.preload = function preload() { return this.el_.preload; }; /** * Set preload attribute * * @param {String} val Value for preload attribute * @method setPreload */ Html5.prototype.setPreload = function setPreload(val) { this.el_.preload = val; }; /** * Get autoplay attribute * * @return {String} * @method autoplay */ Html5.prototype.autoplay = function autoplay() { return this.el_.autoplay; }; /** * Set autoplay attribute * * @param {String} val Value for preload attribute * @method setAutoplay */ Html5.prototype.setAutoplay = function setAutoplay(val) { this.el_.autoplay = val; }; /** * Get controls attribute * * @return {String} * @method controls */ Html5.prototype.controls = function controls() { return this.el_.controls; }; /** * Set controls attribute * * @param {String} val Value for controls attribute * @method setControls */ Html5.prototype.setControls = function setControls(val) { this.el_.controls = !!val; }; /** * Get loop attribute * * @return {String} * @method loop */ Html5.prototype.loop = function loop() { return this.el_.loop; }; /** * Set loop attribute * * @param {String} val Value for loop attribute * @method setLoop */ Html5.prototype.setLoop = function setLoop(val) { this.el_.loop = val; }; /** * Get error value * * @return {String} * @method error */ Html5.prototype.error = function error() { return this.el_.error; }; /** * Get whether or not the player is in the "seeking" state * * @return {Boolean} * @method seeking */ Html5.prototype.seeking = function seeking() { return this.el_.seeking; }; /** * Get a TimeRanges object that represents the * ranges of the media resource to which it is possible * for the user agent to seek. * * @return {TimeRangeObject} * @method seekable */ Html5.prototype.seekable = function seekable() { return this.el_.seekable; }; /** * Get if video ended * * @return {Boolean} * @method ended */ Html5.prototype.ended = function ended() { return this.el_.ended; }; /** * Get the value of the muted content attribute * This attribute has no dynamic effect, it only * controls the default state of the element * * @return {Boolean} * @method defaultMuted */ Html5.prototype.defaultMuted = function defaultMuted() { return this.el_.defaultMuted; }; /** * Get desired speed at which the media resource is to play * * @return {Number} * @method playbackRate */ Html5.prototype.playbackRate = function playbackRate() { return this.el_.playbackRate; }; /** * Returns a TimeRanges object that represents the ranges of the * media resource that the user agent has played. * @return {TimeRangeObject} the range of points on the media * timeline that has been reached through normal playback * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-played */ Html5.prototype.played = function played() { return this.el_.played; }; /** * Set desired speed at which the media resource is to play * * @param {Number} val Speed at which the media resource is to play * @method setPlaybackRate */ Html5.prototype.setPlaybackRate = function setPlaybackRate(val) { this.el_.playbackRate = val; }; /** * Get the current state of network activity for the element, from * the list below * NETWORK_EMPTY (numeric value 0) * NETWORK_IDLE (numeric value 1) * NETWORK_LOADING (numeric value 2) * NETWORK_NO_SOURCE (numeric value 3) * * @return {Number} * @method networkState */ Html5.prototype.networkState = function networkState() { return this.el_.networkState; }; /** * Get a value that expresses the current state of the element * with respect to rendering the current playback position, from * the codes in the list below * HAVE_NOTHING (numeric value 0) * HAVE_METADATA (numeric value 1) * HAVE_CURRENT_DATA (numeric value 2) * HAVE_FUTURE_DATA (numeric value 3) * HAVE_ENOUGH_DATA (numeric value 4) * * @return {Number} * @method readyState */ Html5.prototype.readyState = function readyState() { return this.el_.readyState; }; /** * Get width of video * * @return {Number} * @method videoWidth */ Html5.prototype.videoWidth = function videoWidth() { return this.el_.videoWidth; }; /** * Get height of video * * @return {Number} * @method videoHeight */ Html5.prototype.videoHeight = function videoHeight() { return this.el_.videoHeight; }; /** * Get text tracks * * @return {TextTrackList} * @method textTracks */ Html5.prototype.textTracks = function textTracks() { return _Tech.prototype.textTracks.call(this); }; /** * Creates and returns a text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!this['featuresNativeTextTracks']) { return _Tech.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); }; /** * Creates a remote text track object and returns a html track element * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {HTMLTrackElement} * @method addRemoteTextTrack */ Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (!this['featuresNativeTextTracks']) { return _Tech.prototype.addRemoteTextTrack.call(this, options); } var htmlTrackElement = _globalDocument2['default'].createElement('track'); if (options.kind) { htmlTrackElement.kind = options.kind; } if (options.label) { htmlTrackElement.label = options.label; } if (options.language || options.srclang) { htmlTrackElement.srclang = options.language || options.srclang; } if (options['default']) { htmlTrackElement['default'] = options['default']; } if (options.id) { htmlTrackElement.id = options.id; } if (options.src) { htmlTrackElement.src = options.src; } this.el().appendChild(htmlTrackElement); // store HTMLTrackElement and TextTrack to remote list this.remoteTextTrackEls().addTrackElement_(htmlTrackElement); this.remoteTextTracks().addTrack_(htmlTrackElement.track); return htmlTrackElement; }; /** * Remove remote text track from TextTrackList object * * @param {TextTrackObject} track Texttrack object to remove * @method removeRemoteTextTrack */ Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { if (!this['featuresNativeTextTracks']) { return _Tech.prototype.removeRemoteTextTrack.call(this, track); } var tracks = undefined, i = undefined; var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track); // remove HTMLTrackElement and TextTrack from remote list this.remoteTextTrackEls().removeTrackElement_(trackElement); this.remoteTextTracks().removeTrack_(track); tracks = this.$$('track'); i = tracks.length; while (i--) { if (track === tracks[i] || track === tracks[i].track) { this.el().removeChild(tracks[i]); } } }; return Html5; })(_techJs2['default']); Html5.TEST_VID = _globalDocument2['default'].createElement('video'); var track = _globalDocument2['default'].createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; Html5.TEST_VID.appendChild(track); /* * Check if HTML5 video is supported by this browser/device * * @return {Boolean} */ Html5.isSupported = function () { // IE9 with no Media Player is a LIAR! (#984) try { Html5.TEST_VID['volume'] = 0.5; } catch (e) { return false; } return !!Html5.TEST_VID.canPlayType; }; // Add Source Handler pattern functions to this tech _techJs2['default'].withSourceHandlers(Html5); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Html5} tech The instance of the HTML5 tech */ Html5.nativeSourceHandler = {}; /* * Check if the video element can play the given videotype * * @param {String} type The mimetype to check * @return {String} 'probably', 'maybe', or '' (empty string) */ Html5.nativeSourceHandler.canPlayType = function (type) { // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return Html5.TEST_VID.canPlayType(type); } catch (e) { return ''; } }; /* * Check if the video element can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Html5.nativeSourceHandler.canHandleSource = function (source) { var match, ext; // If a type was provided we should rely on that if (source.type) { return Html5.nativeSourceHandler.canPlayType(source.type); } else if (source.src) { // If no type, fall back to checking 'video/[EXTENSION]' ext = Url.getFileExtension(source.src); return Html5.nativeSourceHandler.canPlayType('video/' + ext); } return ''; }; /* * Pass the source to the video element * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Html5} tech The instance of the Html5 tech */ Html5.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler Html5.registerSourceHandler(Html5.nativeSourceHandler); /* * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * * @return {Boolean} */ Html5.canControlVolume = function () { var volume = Html5.TEST_VID.volume; Html5.TEST_VID.volume = volume / 2 + 0.1; return volume !== Html5.TEST_VID.volume; }; /* * Check if playbackRate is supported in this browser/device. * * @return {Number} [description] */ Html5.canControlPlaybackRate = function () { var playbackRate = Html5.TEST_VID.playbackRate; Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1; return playbackRate !== Html5.TEST_VID.playbackRate; }; /* * Check to see if native text tracks are supported by this browser/device * * @return {Boolean} */ Html5.supportsNativeTextTracks = function () { var supportsTextTracks; // Figure out native text track support // If mode is a number, we cannot change it because it'll disappear from view. // Browsers with numeric modes include IE10 and older (<=2013) samsung android models. // Firefox isn't playing nice either with modifying the mode // TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862 supportsTextTracks = !!Html5.TEST_VID.textTracks; if (supportsTextTracks && Html5.TEST_VID.textTracks.length > 0) { supportsTextTracks = typeof Html5.TEST_VID.textTracks[0]['mode'] !== 'number'; } if (supportsTextTracks && browser.IS_FIREFOX) { supportsTextTracks = false; } if (supportsTextTracks && !('onremovetrack' in Html5.TEST_VID.textTracks)) { supportsTextTracks = false; } return supportsTextTracks; }; /** * An array of events available on the Html5 tech. * * @private * @type {Array} */ Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'volumechange']; /* * Set the tech's volume control support status * * @type {Boolean} */ Html5.prototype['featuresVolumeControl'] = Html5.canControlVolume(); /* * Set the tech's playbackRate support status * * @type {Boolean} */ Html5.prototype['featuresPlaybackRate'] = Html5.canControlPlaybackRate(); /* * Set the tech's status on moving the video element. * In iOS, if you move a video element in the DOM, it breaks video playback. * * @type {Boolean} */ Html5.prototype['movingMediaElementInDOM'] = !browser.IS_IOS; /* * Set the the tech's fullscreen resize support status. * HTML video is able to automatically resize when going to fullscreen. * (No longer appears to be used. Can probably be removed.) */ Html5.prototype['featuresFullscreenResize'] = true; /* * Set the tech's progress event support status * (this disables the manual progress events of the Tech) */ Html5.prototype['featuresProgressEvents'] = true; /* * Sets the tech's status on native text track support * * @type {Boolean} */ Html5.prototype['featuresNativeTextTracks'] = Html5.supportsNativeTextTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // var canPlayType = undefined; var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i; var mp4RE = /^video\/mp4/i; Html5.patchCanPlayType = function () { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (browser.ANDROID_VERSION >= 4.0) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } // Override Android 2.2 and less canPlayType method which is broken if (browser.IS_OLD_ANDROID) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; Html5.unpatchCanPlayType = function () { var r = Html5.TEST_VID.constructor.prototype.canPlayType; Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType; canPlayType = null; return r; }; // by default, patch the video element Html5.patchCanPlayType(); Html5.disposeMediaElement = function (el) { if (!el) { return; } if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while (el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) { // not supported } })(); } }; Html5.resetMediaElement = function (el) { if (!el) { return; } var sources = el.querySelectorAll('source'); var i = sources.length; while (i--) { el.removeChild(sources[i]); } // remove any src reference. // not setting `src=''` because that throws an error el.removeAttribute('src'); if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) {} })(); } }; _component2['default'].registerComponent('Html5', Html5); _techJs2['default'].registerTech('Html5', Html5); exports['default'] = Html5; module.exports = exports['default']; },{"../component":67,"../utils/browser.js":129,"../utils/dom.js":132,"../utils/fn.js":134,"../utils/log.js":137,"../utils/merge-options.js":138,"../utils/url.js":142,"./tech.js":119,"global/document":1,"global/window":2,"object.assign":45}],118:[function(_dereq_,module,exports){ /** * @file loader.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _techJs = _dereq_('./tech.js'); var _techJs2 = _interopRequireDefault(_techJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class MediaLoader */ var MediaLoader = (function (_Component) { _inherits(MediaLoader, _Component); function MediaLoader(player, options, ready) { _classCallCheck(this, MediaLoader); _Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!options.playerOptions['sources'] || options.playerOptions['sources'].length === 0) { for (var i = 0, j = options.playerOptions['techOrder']; i < j.length; i++) { var techName = _utilsToTitleCaseJs2['default'](j[i]); var tech = _techJs2['default'].getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!techName) { tech = _componentJs2['default'].getComponent(techName); } // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech_(techName); break; } } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(options.playerOptions['sources']); } } return MediaLoader; })(_componentJs2['default']); _componentJs2['default'].registerComponent('MediaLoader', MediaLoader); exports['default'] = MediaLoader; module.exports = exports['default']; },{"../component.js":67,"../utils/to-title-case.js":141,"./tech.js":119,"global/window":2}],119:[function(_dereq_,module,exports){ /** * @file tech.js * Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _tracksHtmlTrackElement = _dereq_('../tracks/html-track-element'); var _tracksHtmlTrackElement2 = _interopRequireDefault(_tracksHtmlTrackElement); var _tracksHtmlTrackElementList = _dereq_('../tracks/html-track-element-list'); var _tracksHtmlTrackElementList2 = _interopRequireDefault(_tracksHtmlTrackElementList); var _utilsMergeOptionsJs = _dereq_('../utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); var _tracksTextTrack = _dereq_('../tracks/text-track'); var _tracksTextTrack2 = _interopRequireDefault(_tracksTextTrack); var _tracksTextTrackList = _dereq_('../tracks/text-track-list'); var _tracksTextTrackList2 = _interopRequireDefault(_tracksTextTrackList); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js'); var _utilsBufferJs = _dereq_('../utils/buffer.js'); var _mediaErrorJs = _dereq_('../media-error.js'); var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Base class for media (HTML5 Video, Flash) controllers * * @param {Object=} options Options object * @param {Function=} ready Ready callback function * @extends Component * @class Tech */ var Tech = (function (_Component) { _inherits(Tech, _Component); function Tech() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var ready = arguments.length <= 1 || arguments[1] === undefined ? function () {} : arguments[1]; _classCallCheck(this, Tech); // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; _Component.call(this, null, options, ready); // keep track of whether the current source has played at all to // implement a very limited played() this.hasStarted_ = false; this.on('playing', function () { this.hasStarted_ = true; }); this.on('loadstart', function () { this.hasStarted_ = false; }); this.textTracks_ = options.textTracks; // Manually track progress in cases where the browser/flash player doesn't report it. if (!this.featuresProgressEvents) { this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!this.featuresTimeupdateEvents) { this.manualTimeUpdatesOn(); } if (options.nativeCaptions === false || options.nativeTextTracks === false) { this.featuresNativeTextTracks = false; } if (!this.featuresNativeTextTracks) { this.on('ready', this.emulateTextTracks); } this.initTextTrackListeners(); // Turn on component tap events this.emitTapEvents(); } /* * List of associated text tracks * * @type {Array} * @private */ /* Fallbacks for unsupported event types ================================================================================ */ // Manually trigger progress events based on changes to the buffered amount // Many flash players and older HTML5 browsers don't send progress or progress-like events /** * Turn on progress events * * @method manualProgressOn */ Tech.prototype.manualProgressOn = function manualProgressOn() { this.on('durationchange', this.onDurationChange); this.manualProgress = true; // Trigger progress watching when a source begins loading this.one('ready', this.trackProgress); }; /** * Turn off progress events * * @method manualProgressOff */ Tech.prototype.manualProgressOff = function manualProgressOff() { this.manualProgress = false; this.stopTrackingProgress(); this.off('durationchange', this.onDurationChange); }; /** * Track progress * * @method trackProgress */ Tech.prototype.trackProgress = function trackProgress() { this.stopTrackingProgress(); this.progressInterval = this.setInterval(Fn.bind(this, function () { // Don't trigger unless buffered amount is greater than last time var numBufferedPercent = this.bufferedPercent(); if (this.bufferedPercent_ !== numBufferedPercent) { this.trigger('progress'); } this.bufferedPercent_ = numBufferedPercent; if (numBufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); }; /** * Update duration * * @method onDurationChange */ Tech.prototype.onDurationChange = function onDurationChange() { this.duration_ = this.duration(); }; /** * Create and get TimeRange object for buffering * * @return {TimeRangeObject} * @method buffered */ Tech.prototype.buffered = function buffered() { return _utilsTimeRangesJs.createTimeRange(0, 0); }; /** * Get buffered percent * * @return {Number} * @method bufferedPercent */ Tech.prototype.bufferedPercent = function bufferedPercent() { return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration_); }; /** * Stops tracking progress by clearing progress interval * * @method stopTrackingProgress */ Tech.prototype.stopTrackingProgress = function stopTrackingProgress() { this.clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ /** * Set event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOn */ Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() { this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); }; /** * Remove event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOff */ Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() { this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; /** * Tracks current time * * @method trackCurrentTime */ Tech.prototype.trackCurrentTime = function trackCurrentTime() { if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function () { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; /** * Turn off play progress tracking (when paused or dragging) * * @method stopTrackingCurrentTime */ Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() { this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }; /** * Turn off any manual progress or timeupdate tracking * * @method dispose */ Tech.prototype.dispose = function dispose() { // clear out text tracks because we can't reuse them between techs var textTracks = this.textTracks(); if (textTracks) { var i = textTracks.length; while (i--) { this.removeRemoteTextTrack(textTracks[i]); } } // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } _Component.prototype.dispose.call(this); }; /** * Reset the tech. Removes all sources and resets readyState. * * @method reset */ Tech.prototype.reset = function reset() {}; /** * When invoked without an argument, returns a MediaError object * representing the current error state of the player or null if * there is no error. When invoked with an argument, set the current * error state of the player. * @param {MediaError=} err Optional an error object * @return {MediaError} the current error object or null * @method error */ Tech.prototype.error = function error(err) { if (err !== undefined) { if (err instanceof _mediaErrorJs2['default']) { this.error_ = err; } else { this.error_ = new _mediaErrorJs2['default'](err); } this.trigger('error'); } return this.error_; }; /** * Return the time ranges that have been played through for the * current source. This implementation is incomplete. It does not * track the played time ranges, only whether the source has played * at all or not. * @return {TimeRangeObject} a single time range if this video has * played or an empty set of ranges if not. * @method played */ Tech.prototype.played = function played() { if (this.hasStarted_) { return _utilsTimeRangesJs.createTimeRange(0, 0); } return _utilsTimeRangesJs.createTimeRange(); }; /** * Set current time * * @method setCurrentTime */ Tech.prototype.setCurrentTime = function setCurrentTime() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } }; /** * Initialize texttrack listeners * * @method initTextTrackListeners */ Tech.prototype.initTextTrackListeners = function initTextTrackListeners() { var textTrackListChanges = Fn.bind(this, function () { this.trigger('texttrackchange'); }); var tracks = this.textTracks(); if (!tracks) return; tracks.addEventListener('removetrack', textTrackListChanges); tracks.addEventListener('addtrack', textTrackListChanges); this.on('dispose', Fn.bind(this, function () { tracks.removeEventListener('removetrack', textTrackListChanges); tracks.removeEventListener('addtrack', textTrackListChanges); })); }; /** * Emulate texttracks * * @method emulateTextTracks */ Tech.prototype.emulateTextTracks = function emulateTextTracks() { var _this = this; var tracks = this.textTracks(); if (!tracks) { return; } if (!_globalWindow2['default']['WebVTT'] && this.el().parentNode != null) { (function () { var script = _globalDocument2['default'].createElement('script'); script.src = _this.options_['vtt.js'] || 'https://cdn.rawgit.com/gkatsev/vtt.js/vjs-v0.12.1/dist/vtt.min.js'; script.onload = function () { _this.trigger('vttjsloaded'); }; script.onerror = function () { _this.trigger('vttjserror'); }; _this.on('dispose', function () { script.onload = null; script.onerror = null; }); _this.el().parentNode.appendChild(script); _globalWindow2['default']['WebVTT'] = true; })(); } var updateDisplay = function updateDisplay() { return _this.trigger('texttrackchange'); }; var textTracksChanges = function textTracksChanges() { updateDisplay(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); if (track.mode === 'showing') { track.addEventListener('cuechange', updateDisplay); } } }; textTracksChanges(); tracks.addEventListener('change', textTracksChanges); this.on('dispose', function () { tracks.removeEventListener('change', textTracksChanges); }); }; /* * Provide default methods for text tracks. * * Html5 tech overrides these. */ /** * Get texttracks * * @returns {TextTrackList} * @method textTracks */ Tech.prototype.textTracks = function textTracks() { this.textTracks_ = this.textTracks_ || new _tracksTextTrackList2['default'](); return this.textTracks_; }; /** * Get remote texttracks * * @returns {TextTrackList} * @method remoteTextTracks */ Tech.prototype.remoteTextTracks = function remoteTextTracks() { this.remoteTextTracks_ = this.remoteTextTracks_ || new _tracksTextTrackList2['default'](); return this.remoteTextTracks_; }; /** * Get remote htmltrackelements * * @returns {HTMLTrackElementList} * @method remoteTextTrackEls */ Tech.prototype.remoteTextTrackEls = function remoteTextTrackEls() { this.remoteTextTrackEls_ = this.remoteTextTrackEls_ || new _tracksHtmlTrackElementList2['default'](); return this.remoteTextTrackEls_; }; /** * Creates and returns a remote text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; /** * Creates a remote text track object and returns a emulated html track element * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {HTMLTrackElement} * @method addRemoteTextTrack */ Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { var track = _utilsMergeOptionsJs2['default'](options, { tech: this }); var htmlTrackElement = new _tracksHtmlTrackElement2['default'](track); // store HTMLTrackElement and TextTrack to remote list this.remoteTextTrackEls().addTrackElement_(htmlTrackElement); this.remoteTextTracks().addTrack_(htmlTrackElement.track); // must come after remoteTextTracks() this.textTracks().addTrack_(htmlTrackElement.track); return htmlTrackElement; }; /** * Remove remote texttrack * * @param {TextTrackObject} track Texttrack to remove * @method removeRemoteTextTrack */ Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.textTracks().removeTrack_(track); var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track); // remove HTMLTrackElement and TextTrack from remote list this.remoteTextTrackEls().removeTrackElement_(trackElement); this.remoteTextTracks().removeTrack_(track); }; /** * Provide a default setPoster method for techs * Poster support for techs should be optional, so we don't want techs to * break if they don't have a way to set a poster. * * @method setPoster */ Tech.prototype.setPoster = function setPoster() {}; /* * Check if the tech can support the given type * * The base tech does not support any type, but source handlers might * overwrite this. * * @param {String} type The mimetype to check * @return {String} 'probably', 'maybe', or '' (empty string) */ Tech.prototype.canPlayType = function canPlayType() { return ''; }; /* * Return whether the argument is a Tech or not. * Can be passed either a Class like `Html5` or a instance like `player.tech_` * * @param {Object} component An item to check * @return {Boolean} Whether it is a tech or not */ Tech.isTech = function isTech(component) { return component.prototype instanceof Tech || component instanceof Tech || component === Tech; }; /** * Registers a Tech * * @param {String} name Name of the Tech to register * @param {Object} tech The tech to register * @static * @method registerComponent */ Tech.registerTech = function registerTech(name, tech) { if (!Tech.techs_) { Tech.techs_ = {}; } if (!Tech.isTech(tech)) { throw new Error('Tech ' + name + ' must be a Tech'); } Tech.techs_[name] = tech; return tech; }; /** * Gets a component by name * * @param {String} name Name of the component to get * @return {Component} * @static * @method getComponent */ Tech.getTech = function getTech(name) { if (Tech.techs_ && Tech.techs_[name]) { return Tech.techs_[name]; } if (_globalWindow2['default'] && _globalWindow2['default'].videojs && _globalWindow2['default'].videojs[name]) { _utilsLogJs2['default'].warn('The ' + name + ' tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)'); return _globalWindow2['default'].videojs[name]; } }; return Tech; })(_component2['default']); Tech.prototype.textTracks_; var createTrackHelper = function createTrackHelper(self, kind, label, language) { var options = arguments.length <= 4 || arguments[4] === undefined ? {} : arguments[4]; var tracks = self.textTracks(); options.kind = kind; if (label) { options.label = label; } if (language) { options.language = language; } options.tech = self; var track = new _tracksTextTrack2['default'](options); tracks.addTrack_(track); return track; }; Tech.prototype.featuresVolumeControl = true; // Resizing plugins using request fullscreen reloads the plugin Tech.prototype.featuresFullscreenResize = false; Tech.prototype.featuresPlaybackRate = false; // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf Tech.prototype.featuresProgressEvents = false; Tech.prototype.featuresTimeupdateEvents = false; Tech.prototype.featuresNativeTextTracks = false; /* * A functional mixin for techs that want to use the Source Handler pattern. * * ##### EXAMPLE: * * Tech.withSourceHandlers.call(MyTech); * */ Tech.withSourceHandlers = function (_Tech) { /* * Register a source handler * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * @param {Function} handler The source handler * @param {Boolean} first Register it before any existing handlers */ _Tech.registerSourceHandler = function (handler, index) { var handlers = _Tech.sourceHandlers; if (!handlers) { handlers = _Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /* * Check if the tech can support the given type * @param {String} type The mimetype to check * @return {String} 'probably', 'maybe', or '' (empty string) */ _Tech.canPlayType = function (type) { var handlers = _Tech.sourceHandlers || []; var can = undefined; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canPlayType(type); if (can) { return can; } } return ''; }; /* * Return the first source handler that supports the source * TODO: Answer question: should 'probably' be prioritized over 'maybe' * @param {Object} source The source object * @returns {Object} The first source handler that supports the source * @returns {null} Null if no source handler is found */ _Tech.selectSourceHandler = function (source) { var handlers = _Tech.sourceHandlers || []; var can = undefined; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source); if (can) { return handlers[i]; } } return null; }; /* * Check if the tech can support the given source * @param {Object} srcObj The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ _Tech.canPlaySource = function (srcObj) { var sh = _Tech.selectSourceHandler(srcObj); if (sh) { return sh.canHandleSource(srcObj); } return ''; }; /* * When using a source handler, prefer its implementation of * any function normally provided by the tech. */ var deferrable = ['seekable', 'duration']; deferrable.forEach(function (fnName) { var originalFn = this[fnName]; if (typeof originalFn !== 'function') { return; } this[fnName] = function () { if (this.sourceHandler_ && this.sourceHandler_[fnName]) { return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments); } return originalFn.apply(this, arguments); }; }, _Tech.prototype); /* * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * @param {Object} source A source object with src and type keys * @return {Tech} self */ _Tech.prototype.setSource = function (source) { var sh = _Tech.selectSourceHandler(source); if (!sh) { // Fall back to a native source hander when unsupported sources are // deliberately set if (_Tech.nativeSourceHandler) { sh = _Tech.nativeSourceHandler; } else { _utilsLogJs2['default'].error('No source hander found for the current source.'); } } // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); this.currentSource_ = source; this.sourceHandler_ = sh.handleSource(source, this); this.on('dispose', this.disposeSourceHandler); return this; }; /* * Clean up any existing source handler */ _Tech.prototype.disposeSourceHandler = function () { if (this.sourceHandler_ && this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); } }; }; _component2['default'].registerComponent('Tech', Tech); // Old name for Tech _component2['default'].registerComponent('MediaTechController', Tech); Tech.registerTech('Tech', Tech); exports['default'] = Tech; module.exports = exports['default']; },{"../component":67,"../media-error.js":103,"../tracks/html-track-element":121,"../tracks/html-track-element-list":120,"../tracks/text-track":128,"../tracks/text-track-list":126,"../utils/buffer.js":130,"../utils/fn.js":134,"../utils/log.js":137,"../utils/merge-options.js":138,"../utils/time-ranges.js":140,"global/document":1,"global/window":2}],120:[function(_dereq_,module,exports){ /** * @file html-track-element-list.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var HtmlTrackElementList = (function () { function HtmlTrackElementList() { var trackElements = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; _classCallCheck(this, HtmlTrackElementList); var list = this; if (browser.IS_IE8) { list = _globalDocument2['default'].createElement('custom'); for (var prop in HtmlTrackElementList.prototype) { if (prop !== 'constructor') { list[prop] = HtmlTrackElementList.prototype[prop]; } } } list.trackElements_ = []; Object.defineProperty(list, 'length', { get: function get() { return this.trackElements_.length; } }); for (var i = 0, _length = trackElements.length; i < _length; i++) { list.addTrackElement_(trackElements[i]); } if (browser.IS_IE8) { return list; } } HtmlTrackElementList.prototype.addTrackElement_ = function addTrackElement_(trackElement) { this.trackElements_.push(trackElement); }; HtmlTrackElementList.prototype.getTrackElementByTrack_ = function getTrackElementByTrack_(track) { var trackElement_ = undefined; for (var i = 0, _length2 = this.trackElements_.length; i < _length2; i++) { if (track === this.trackElements_[i].track) { trackElement_ = this.trackElements_[i]; break; } } return trackElement_; }; HtmlTrackElementList.prototype.removeTrackElement_ = function removeTrackElement_(trackElement) { for (var i = 0, _length3 = this.trackElements_.length; i < _length3; i++) { if (trackElement === this.trackElements_[i]) { this.trackElements_.splice(i, 1); break; } } }; return HtmlTrackElementList; })(); exports['default'] = HtmlTrackElementList; module.exports = exports['default']; },{"../utils/browser.js":129,"global/document":1}],121:[function(_dereq_,module,exports){ /** * @file html-track-element.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _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 _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _eventTarget = _dereq_('../event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _tracksTextTrack = _dereq_('../tracks/text-track'); var _tracksTextTrack2 = _interopRequireDefault(_tracksTextTrack); var NONE = 0; var LOADING = 1; var LOADED = 2; var ERROR = 3; /** * https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement * * interface HTMLTrackElement : HTMLElement { * attribute DOMString kind; * attribute DOMString src; * attribute DOMString srclang; * attribute DOMString label; * attribute boolean default; * * const unsigned short NONE = 0; * const unsigned short LOADING = 1; * const unsigned short LOADED = 2; * const unsigned short ERROR = 3; * readonly attribute unsigned short readyState; * * readonly attribute TextTrack track; * }; * * @param {Object} options TextTrack configuration * @class HTMLTrackElement */ var HTMLTrackElement = (function (_EventTarget) { _inherits(HTMLTrackElement, _EventTarget); function HTMLTrackElement() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; _classCallCheck(this, HTMLTrackElement); _EventTarget.call(this); var readyState = undefined, trackElement = this; if (browser.IS_IE8) { trackElement = _globalDocument2['default'].createElement('custom'); for (var prop in HTMLTrackElement.prototype) { if (prop !== 'constructor') { trackElement[prop] = HTMLTrackElement.prototype[prop]; } } } var track = new _tracksTextTrack2['default'](options); trackElement.kind = track.kind; trackElement.src = track.src; trackElement.srclang = track.language; trackElement.label = track.label; trackElement['default'] = track['default']; Object.defineProperty(trackElement, 'readyState', { get: function get() { return readyState; } }); Object.defineProperty(trackElement, 'track', { get: function get() { return track; } }); readyState = NONE; track.addEventListener('loadeddata', function () { readyState = LOADED; trackElement.trigger({ type: 'load', target: trackElement }); }); if (browser.IS_IE8) { return trackElement; } } return HTMLTrackElement; })(_eventTarget2['default']); HTMLTrackElement.prototype.allowedEvents_ = { load: 'load' }; HTMLTrackElement.NONE = NONE; HTMLTrackElement.LOADING = LOADING; HTMLTrackElement.LOADED = LOADED; HTMLTrackElement.ERROR = ERROR; exports['default'] = HTMLTrackElement; module.exports = exports['default']; },{"../event-target":99,"../tracks/text-track":128,"../utils/browser.js":129,"global/document":1}],122:[function(_dereq_,module,exports){ /** * @file text-track-cue-list.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * A List of text track cues as defined in: * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist * * interface TextTrackCueList { * readonly attribute unsigned long length; * getter TextTrackCue (unsigned long index); * TextTrackCue? getCueById(DOMString id); * }; * * @param {Array} cues A list of cues to be initialized with * @class TextTrackCueList */ var TextTrackCueList = (function () { function TextTrackCueList(cues) { _classCallCheck(this, TextTrackCueList); var list = this; if (browser.IS_IE8) { list = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrackCueList.prototype) { if (prop !== 'constructor') { list[prop] = TextTrackCueList.prototype[prop]; } } } TextTrackCueList.prototype.setCues_.call(list, cues); Object.defineProperty(list, 'length', { get: function get() { return this.length_; } }); if (browser.IS_IE8) { return list; } } /** * A setter for cues in this list * * @param {Array} cues an array of cues * @method setCues_ * @private */ TextTrackCueList.prototype.setCues_ = function setCues_(cues) { var oldLength = this.length || 0; var i = 0; var l = cues.length; this.cues_ = cues; this.length_ = cues.length; var defineProp = function defineProp(index) { if (!('' + index in this)) { Object.defineProperty(this, '' + index, { get: function get() { return this.cues_[index]; } }); } }; if (oldLength < l) { i = oldLength; for (; i < l; i++) { defineProp.call(this, i); } } }; /** * Get a cue that is currently in the Cue list by id * * @param {String} id * @method getCueById * @return {Object} a single cue */ TextTrackCueList.prototype.getCueById = function getCueById(id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; return TextTrackCueList; })(); exports['default'] = TextTrackCueList; module.exports = exports['default']; },{"../utils/browser.js":129,"global/document":1}],123:[function(_dereq_,module,exports){ /** * @file text-track-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _menuMenuJs = _dereq_('../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _menuMenuItemJs = _dereq_('../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _menuMenuButtonJs = _dereq_('../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; /** * The component for displaying text track cues * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class TextTrackDisplay */ var TextTrackDisplay = (function (_Component) { _inherits(TextTrackDisplay, _Component); function TextTrackDisplay(player, options, ready) { _classCallCheck(this, TextTrackDisplay); _Component.call(this, player, options, ready); player.on('loadstart', Fn.bind(this, this.toggleDisplay)); player.on('texttrackchange', Fn.bind(this, this.updateDisplay)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(Fn.bind(this, function () { if (player.tech_ && player.tech_['featuresNativeTextTracks']) { this.hide(); return; } player.on('fullscreenchange', Fn.bind(this, this.updateDisplay)); var tracks = this.options_.playerOptions['tracks'] || []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; this.player_.addRemoteTextTrack(track); } })); } /** * Add cue HTML to display * * @param {Number} color Hex number for color, like #f0e * @param {Number} opacity Value for opacity,0.0 - 1.0 * @return {RGBAColor} In the form 'rgba(255, 0, 0, 0.3)' * @method constructColor */ /** * Toggle display texttracks * * @method toggleDisplay */ TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() { if (this.player_.tech_ && this.player_.tech_['featuresNativeTextTracks']) { this.hide(); } else { this.show(); } }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; /** * Clear display texttracks * * @method clearDisplay */ TextTrackDisplay.prototype.clearDisplay = function clearDisplay() { if (typeof _globalWindow2['default']['WebVTT'] === 'function') { _globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], [], this.el_); } }; /** * Update display texttracks * * @method updateDisplay */ TextTrackDisplay.prototype.updateDisplay = function updateDisplay() { var tracks = this.player_.textTracks(); this.clearDisplay(); if (!tracks) { return; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['mode'] === 'showing') { this.updateForTrack(track); } } }; /** * Add texttrack to texttrack list * * @param {TextTrackObject} track Texttrack object to be added to list * @method updateForTrack */ TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) { if (typeof _globalWindow2['default']['WebVTT'] !== 'function' || !track['activeCues']) { return; } var overrides = this.player_['textTrackSettings'].getValues(); var cues = []; for (var _i = 0; _i < track['activeCues'].length; _i++) { cues.push(track['activeCues'][_i]); } _globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], track['activeCues'], this.el_); var i = cues.length; while (i--) { var cue = cues[i]; if (!cue) { continue; } var cueDiv = cue.displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { var fontSize = _globalWindow2['default'].parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } }; return TextTrackDisplay; })(_component2['default']); function constructColor(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; } /** * Try to update style * Some style changes will throw an error, particularly in IE8. Those should be noops. * * @param {Element} el The element to be styles * @param {CSSProperty} style The CSS property to be styled * @param {CSSStyle} rule The actual style to be applied to the property * @method tryUpdateStyle */ function tryUpdateStyle(el, style, rule) { // try { el.style[style] = rule; } catch (e) {} } _component2['default'].registerComponent('TextTrackDisplay', TextTrackDisplay); exports['default'] = TextTrackDisplay; module.exports = exports['default']; },{"../component":67,"../menu/menu-button.js":104,"../menu/menu-item.js":105,"../menu/menu.js":106,"../utils/fn.js":134,"global/document":1,"global/window":2}],124:[function(_dereq_,module,exports){ /** * @file text-track-enums.js */ /** * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * * enum TextTrackMode { "disabled", "hidden", "showing" }; */ 'use strict'; exports.__esModule = true; var TextTrackMode = { disabled: 'disabled', hidden: 'hidden', showing: 'showing' }; /** * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind * * enum TextTrackKind { * "subtitles", * "captions", * "descriptions", * "chapters", * "metadata" * }; */ var TextTrackKind = { subtitles: 'subtitles', captions: 'captions', descriptions: 'descriptions', chapters: 'chapters', metadata: 'metadata' }; /* jshint ignore:start */ // we ignore jshint here because it does not see // TextTrackMode or TextTrackKind as defined here somehow... exports.TextTrackMode = TextTrackMode; exports.TextTrackKind = TextTrackKind; /* jshint ignore:end */ },{}],125:[function(_dereq_,module,exports){ /** * Utilities for capturing text track state and re-creating tracks * based on a capture. * * @file text-track-list-converter.js */ /** * Examine a single text track and return a JSON-compatible javascript * object that represents the text track's state. * @param track {TextTrackObject} the text track to query * @return {Object} a serializable javascript representation of the * @private */ 'use strict'; exports.__esModule = true; var trackToJson_ = function trackToJson_(track) { var ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce(function (acc, prop, i) { if (track[prop]) { acc[prop] = track[prop]; } return acc; }, { cues: track.cues && Array.prototype.map.call(track.cues, function (cue) { return { startTime: cue.startTime, endTime: cue.endTime, text: cue.text, id: cue.id }; }) }); return ret; }; /** * Examine a tech and return a JSON-compatible javascript array that * represents the state of all text tracks currently configured. The * return array is compatible with `jsonToTextTracks`. * @param tech {tech} the tech object to query * @return {Array} a serializable javascript representation of the * @function textTracksToJson */ var textTracksToJson = function textTracksToJson(tech) { var trackEls = tech.$$('track'); var trackObjs = Array.prototype.map.call(trackEls, function (t) { return t.track; }); var tracks = Array.prototype.map.call(trackEls, function (trackEl) { var json = trackToJson_(trackEl.track); if (trackEl.src) { json.src = trackEl.src; } return json; }); return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) { return trackObjs.indexOf(track) === -1; }).map(trackToJson_)); }; /** * Creates a set of remote text tracks on a tech based on an array of * javascript text track representations. * @param json {Array} an array of text track representation objects, * like those that would be produced by `textTracksToJson` * @param tech {tech} the tech to create text tracks on * @function jsonToTextTracks */ var jsonToTextTracks = function jsonToTextTracks(json, tech) { json.forEach(function (track) { var addedTrack = tech.addRemoteTextTrack(track).track; if (!track.src && track.cues) { track.cues.forEach(function (cue) { return addedTrack.addCue(cue); }); } }); return tech.textTracks(); }; exports['default'] = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ }; module.exports = exports['default']; },{}],126:[function(_dereq_,module,exports){ /** * @file text-track-list.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _eventTarget = _dereq_('../event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * A text track list as defined in: * https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist * * interface TextTrackList : EventTarget { * readonly attribute unsigned long length; * getter TextTrack (unsigned long index); * TextTrack? getTrackById(DOMString id); * * attribute EventHandler onchange; * attribute EventHandler onaddtrack; * attribute EventHandler onremovetrack; * }; * * @param {Track[]} tracks A list of tracks to initialize the list with * @extends EventTarget * @class TextTrackList */ var TextTrackList = (function (_EventTarget) { _inherits(TextTrackList, _EventTarget); function TextTrackList() { var tracks = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; _classCallCheck(this, TextTrackList); _EventTarget.call(this); var list = this; if (browser.IS_IE8) { list = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrackList.prototype) { if (prop !== 'constructor') { list[prop] = TextTrackList.prototype[prop]; } } } list.tracks_ = []; Object.defineProperty(list, 'length', { get: function get() { return this.tracks_.length; } }); for (var i = 0; i < tracks.length; i++) { list.addTrack_(tracks[i]); } if (browser.IS_IE8) { return list; } } /** * change - One or more tracks in the track list have been enabled or disabled. * addtrack - A track has been added to the track list. * removetrack - A track has been removed from the track list. */ /** * Add TextTrack from TextTrackList * * @param {TextTrack} track * @method addTrack_ * @private */ TextTrackList.prototype.addTrack_ = function addTrack_(track) { var index = this.tracks_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.tracks_[index]; } }); } track.addEventListener('modechange', Fn.bind(this, function () { this.trigger('change'); })); this.tracks_.push(track); this.trigger({ track: track, type: 'addtrack' }); }; /** * Remove TextTrack from TextTrackList * NOTE: Be mindful of what is passed in as it may be a HTMLTrackElement * * @param {TextTrack} rtrack * @method removeTrack_ * @private */ TextTrackList.prototype.removeTrack_ = function removeTrack_(rtrack) { var track = undefined; for (var i = 0, l = this.length; i < l; i++) { if (this[i] === rtrack) { track = this[i]; if (track.off) { track.off(); } this.tracks_.splice(i, 1); break; } } if (!track) { return; } this.trigger({ track: track, type: 'removetrack' }); }; /** * Get a TextTrack from TextTrackList by a tracks id * * @param {String} id - the id of the track to get * @method getTrackById * @return {TextTrack} * @private */ TextTrackList.prototype.getTrackById = function getTrackById(id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var track = this[i]; if (track.id === id) { result = track; break; } } return result; }; return TextTrackList; })(_eventTarget2['default']); TextTrackList.prototype.allowedEvents_ = { change: 'change', addtrack: 'addtrack', removetrack: 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection for (var _event in TextTrackList.prototype.allowedEvents_) { TextTrackList.prototype['on' + _event] = null; } exports['default'] = TextTrackList; module.exports = exports['default']; },{"../event-target":99,"../utils/browser.js":129,"../utils/fn.js":134,"global/document":1}],127:[function(_dereq_,module,exports){ /** * @file text-track-settings.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsEventsJs = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple'); var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * Manipulate settings of texttracks * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class TextTrackSettings */ var TextTrackSettings = (function (_Component) { _inherits(TextTrackSettings, _Component); function TextTrackSettings(player, options) { _classCallCheck(this, TextTrackSettings); _Component.call(this, player, options); this.hide(); // Grab `persistTextTrackSettings` from the player options if not passed in child options if (options.persistTextTrackSettings === undefined) { this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings; } Events.on(this.$('.vjs-done-button'), 'click', Fn.bind(this, function () { this.saveSettings(); this.hide(); })); Events.on(this.$('.vjs-default-button'), 'click', Fn.bind(this, function () { this.$('.vjs-fg-color > select').selectedIndex = 0; this.$('.vjs-bg-color > select').selectedIndex = 0; this.$('.window-color > select').selectedIndex = 0; this.$('.vjs-text-opacity > select').selectedIndex = 0; this.$('.vjs-bg-opacity > select').selectedIndex = 0; this.$('.vjs-window-opacity > select').selectedIndex = 0; this.$('.vjs-edge-style select').selectedIndex = 0; this.$('.vjs-font-family select').selectedIndex = 0; this.$('.vjs-font-percent select').selectedIndex = 2; this.updateDisplay(); })); Events.on(this.$('.vjs-fg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.$('.vjs-bg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.$('.window-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.$('.vjs-text-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.$('.vjs-bg-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.$('.vjs-window-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.$('.vjs-font-percent select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.$('.vjs-edge-style select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.$('.vjs-font-family select'), 'change', Fn.bind(this, this.updateDisplay)); if (this.options_.persistTextTrackSettings) { this.restoreSettings(); } } /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackSettings.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-caption-settings vjs-modal-overlay', innerHTML: captionOptionsMenuTemplate() }); }; /** * Get texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @return {Object} * @method getValues */ TextTrackSettings.prototype.getValues = function getValues() { var textEdge = getSelectedOptionValue(this.$('.vjs-edge-style select')); var fontFamily = getSelectedOptionValue(this.$('.vjs-font-family select')); var fgColor = getSelectedOptionValue(this.$('.vjs-fg-color > select')); var textOpacity = getSelectedOptionValue(this.$('.vjs-text-opacity > select')); var bgColor = getSelectedOptionValue(this.$('.vjs-bg-color > select')); var bgOpacity = getSelectedOptionValue(this.$('.vjs-bg-opacity > select')); var windowColor = getSelectedOptionValue(this.$('.window-color > select')); var windowOpacity = getSelectedOptionValue(this.$('.vjs-window-opacity > select')); var fontPercent = _globalWindow2['default']['parseFloat'](getSelectedOptionValue(this.$('.vjs-font-percent > select'))); var result = { 'backgroundOpacity': bgOpacity, 'textOpacity': textOpacity, 'windowOpacity': windowOpacity, 'edgeStyle': textEdge, 'fontFamily': fontFamily, 'color': fgColor, 'backgroundColor': bgColor, 'windowColor': windowColor, 'fontPercent': fontPercent }; for (var _name in result) { if (result[_name] === '' || result[_name] === 'none' || _name === 'fontPercent' && result[_name] === 1.00) { delete result[_name]; } } return result; }; /** * Set texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @param {Object} values Object with texttrack setting values * @method setValues */ TextTrackSettings.prototype.setValues = function setValues(values) { setSelectedOption(this.$('.vjs-edge-style select'), values.edgeStyle); setSelectedOption(this.$('.vjs-font-family select'), values.fontFamily); setSelectedOption(this.$('.vjs-fg-color > select'), values.color); setSelectedOption(this.$('.vjs-text-opacity > select'), values.textOpacity); setSelectedOption(this.$('.vjs-bg-color > select'), values.backgroundColor); setSelectedOption(this.$('.vjs-bg-opacity > select'), values.backgroundOpacity); setSelectedOption(this.$('.window-color > select'), values.windowColor); setSelectedOption(this.$('.vjs-window-opacity > select'), values.windowOpacity); var fontPercent = values.fontPercent; if (fontPercent) { fontPercent = fontPercent.toFixed(2); } setSelectedOption(this.$('.vjs-font-percent > select'), fontPercent); }; /** * Restore texttrack settings * * @method restoreSettings */ TextTrackSettings.prototype.restoreSettings = function restoreSettings() { var err = undefined, values = undefined; try { var _safeParseTuple = _safeJsonParseTuple2['default'](_globalWindow2['default'].localStorage.getItem('vjs-text-track-settings')); err = _safeParseTuple[0]; values = _safeParseTuple[1]; if (err) { _utilsLogJs2['default'].error(err); } } catch (e) { _utilsLogJs2['default'].warn(e); } if (values) { this.setValues(values); } }; /** * Save texttrack settings to local storage * * @method saveSettings */ TextTrackSettings.prototype.saveSettings = function saveSettings() { if (!this.options_.persistTextTrackSettings) { return; } var values = this.getValues(); try { if (Object.getOwnPropertyNames(values).length > 0) { _globalWindow2['default'].localStorage.setItem('vjs-text-track-settings', JSON.stringify(values)); } else { _globalWindow2['default'].localStorage.removeItem('vjs-text-track-settings'); } } catch (e) { _utilsLogJs2['default'].warn(e); } }; /** * Update display of texttrack settings * * @method updateDisplay */ TextTrackSettings.prototype.updateDisplay = function updateDisplay() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } }; return TextTrackSettings; })(_component2['default']); _component2['default'].registerComponent('TextTrackSettings', TextTrackSettings); function getSelectedOptionValue(target) { var selectedOption = undefined; // not all browsers support selectedOptions, so, fallback to options if (target.selectedOptions) { selectedOption = target.selectedOptions[0]; } else if (target.options) { selectedOption = target.options[target.options.selectedIndex]; } return selectedOption.value; } function setSelectedOption(target, value) { if (!value) { return; } var i = undefined; for (i = 0; i < target.options.length; i++) { var option = target.options[i]; if (option.value === value) { break; } } target.selectedIndex = i; } function captionOptionsMenuTemplate() { var template = '<div class="vjs-tracksettings">\n <div class="vjs-tracksettings-colors">\n <div class="vjs-fg-color vjs-tracksetting">\n <label class="vjs-label">Foreground</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-text-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Opaque</option>\n </select>\n </span>\n </div> <!-- vjs-fg-color -->\n <div class="vjs-bg-color vjs-tracksetting">\n <label class="vjs-label">Background</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-bg-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-bg-color -->\n <div class="window-color vjs-tracksetting">\n <label class="vjs-label">Window</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-window-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-window-color -->\n </div> <!-- vjs-tracksettings -->\n <div class="vjs-tracksettings-font">\n <div class="vjs-font-percent vjs-tracksetting">\n <label class="vjs-label">Font Size</label>\n <select>\n <option value="0.50">50%</option>\n <option value="0.75">75%</option>\n <option value="1.00" selected>100%</option>\n <option value="1.25">125%</option>\n <option value="1.50">150%</option>\n <option value="1.75">175%</option>\n <option value="2.00">200%</option>\n <option value="3.00">300%</option>\n <option value="4.00">400%</option>\n </select>\n </div> <!-- vjs-font-percent -->\n <div class="vjs-edge-style vjs-tracksetting">\n <label class="vjs-label">Text Edge Style</label>\n <select>\n <option value="none">None</option>\n <option value="raised">Raised</option>\n <option value="depressed">Depressed</option>\n <option value="uniform">Uniform</option>\n <option value="dropshadow">Dropshadow</option>\n </select>\n </div> <!-- vjs-edge-style -->\n <div class="vjs-font-family vjs-tracksetting">\n <label class="vjs-label">Font Family</label>\n <select>\n <option value="">Default</option>\n <option value="monospaceSerif">Monospace Serif</option>\n <option value="proportionalSerif">Proportional Serif</option>\n <option value="monospaceSansSerif">Monospace Sans-Serif</option>\n <option value="proportionalSansSerif">Proportional Sans-Serif</option>\n <option value="casual">Casual</option>\n <option value="script">Script</option>\n <option value="small-caps">Small Caps</option>\n </select>\n </div> <!-- vjs-font-family -->\n </div>\n </div>\n <div class="vjs-tracksettings-controls">\n <button class="vjs-default-button">Defaults</button>\n <button class="vjs-done-button">Done</button>\n </div>'; return template; } exports['default'] = TextTrackSettings; module.exports = exports['default']; },{"../component":67,"../utils/events.js":133,"../utils/fn.js":134,"../utils/log.js":137,"global/window":2,"safe-json-parse/tuple":54}],128:[function(_dereq_,module,exports){ /** * @file text-track.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } 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 _textTrackCueList = _dereq_('./text-track-cue-list'); var _textTrackCueList2 = _interopRequireDefault(_textTrackCueList); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('../utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _textTrackEnums = _dereq_('./text-track-enums'); var TextTrackEnum = _interopRequireWildcard(_textTrackEnums); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _eventTarget = _dereq_('../event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsUrlJs = _dereq_('../utils/url.js'); var _xhr = _dereq_('xhr'); var _xhr2 = _interopRequireDefault(_xhr); /** * takes a webvtt file contents and parses it into cues * * @param {String} srcContent webVTT file contents * @param {Track} track track to addcues to */ var parseCues = function parseCues(srcContent, track) { var parser = new _globalWindow2['default'].WebVTT.Parser(_globalWindow2['default'], _globalWindow2['default'].vttjs, _globalWindow2['default'].WebVTT.StringDecoder()); parser.oncue = function (cue) { track.addCue(cue); }; parser.onparsingerror = function (error) { _utilsLogJs2['default'].error(error); }; parser.onflush = function () { track.trigger({ type: 'loadeddata', target: track }); }; parser.parse(srcContent); parser.flush(); }; /** * load a track from a specifed url * * @param {String} src url to load track from * @param {Track} track track to addcues to */ var loadTrack = function loadTrack(src, track) { var opts = { uri: src }; var crossOrigin = _utilsUrlJs.isCrossOrigin(src); if (crossOrigin) { opts.cors = crossOrigin; } _xhr2['default'](opts, Fn.bind(this, function (err, response, responseBody) { if (err) { return _utilsLogJs2['default'].error(err, response); } track.loaded_ = true; // Make sure that vttjs has loaded, otherwise, wait till it finished loading // NOTE: this is only used for the alt/video.novtt.js build if (typeof _globalWindow2['default'].WebVTT !== 'function') { if (track.tech_) { (function () { var loadHandler = function loadHandler() { return parseCues(responseBody, track); }; track.tech_.on('vttjsloaded', loadHandler); track.tech_.on('vttjserror', function () { _utilsLogJs2['default'].error('vttjs failed to load, stopping trying to process ' + track.src); track.tech_.off('vttjsloaded', loadHandler); }); })(); } } else { parseCues(responseBody, track); } })); }; /** * A single text track as defined in: * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack * * interface TextTrack : EventTarget { * readonly attribute TextTrackKind kind; * readonly attribute DOMString label; * readonly attribute DOMString language; * * readonly attribute DOMString id; * readonly attribute DOMString inBandMetadataTrackDispatchType; * * attribute TextTrackMode mode; * * readonly attribute TextTrackCueList? cues; * readonly attribute TextTrackCueList? activeCues; * * void addCue(TextTrackCue cue); * void removeCue(TextTrackCue cue); * * attribute EventHandler oncuechange; * }; * * @param {Object=} options Object of option names and values * @extends EventTarget * @class TextTrack */ var TextTrack = (function (_EventTarget) { _inherits(TextTrack, _EventTarget); function TextTrack() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; _classCallCheck(this, TextTrack); _EventTarget.call(this); if (!options.tech) { throw new Error('A tech was not provided.'); } var tt = this; if (browser.IS_IE8) { tt = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrack.prototype) { if (prop !== 'constructor') { tt[prop] = TextTrack.prototype[prop]; } } } tt.tech_ = options.tech; var mode = TextTrackEnum.TextTrackMode[options.mode] || 'disabled'; var kind = TextTrackEnum.TextTrackKind[options.kind] || 'subtitles'; var label = options.label || ''; var language = options.language || options.srclang || ''; var id = options.id || 'vjs_text_track_' + Guid.newGUID(); if (kind === 'metadata' || kind === 'chapters') { mode = 'hidden'; } tt.cues_ = []; tt.activeCues_ = []; var cues = new _textTrackCueList2['default'](tt.cues_); var activeCues = new _textTrackCueList2['default'](tt.activeCues_); var changed = false; var timeupdateHandler = Fn.bind(tt, function () { this.activeCues; if (changed) { this.trigger('cuechange'); changed = false; } }); if (mode !== 'disabled') { tt.tech_.on('timeupdate', timeupdateHandler); } Object.defineProperty(tt, 'kind', { get: function get() { return kind; }, set: function set() {} }); Object.defineProperty(tt, 'label', { get: function get() { return label; }, set: function set() {} }); Object.defineProperty(tt, 'language', { get: function get() { return language; }, set: function set() {} }); Object.defineProperty(tt, 'id', { get: function get() { return id; }, set: function set() {} }); Object.defineProperty(tt, 'mode', { get: function get() { return mode; }, set: function set(newMode) { if (!TextTrackEnum.TextTrackMode[newMode]) { return; } mode = newMode; if (mode === 'showing') { this.tech_.on('timeupdate', timeupdateHandler); } this.trigger('modechange'); } }); Object.defineProperty(tt, 'cues', { get: function get() { if (!this.loaded_) { return null; } return cues; }, set: function set() {} }); Object.defineProperty(tt, 'activeCues', { get: function get() { if (!this.loaded_) { return null; } // nothing to do if (this.cues.length === 0) { return activeCues; } var ct = this.tech_.currentTime(); var active = []; for (var i = 0, l = this.cues.length; i < l; i++) { var cue = this.cues[i]; if (cue.startTime <= ct && cue.endTime >= ct) { active.push(cue); } else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (var i = 0; i < active.length; i++) { if (this.activeCues_.indexOf(active[i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, set: function set() {} }); if (options.src) { tt.src = options.src; loadTrack(options.src, tt); } else { tt.loaded_ = true; } if (browser.IS_IE8) { return tt; } } /** * cuechange - One or more cues in the track have become active or stopped being active. */ /** * add a cue to the internal list of cues * * @param {Object} cue the cue to add to our internal list * @method addCue */ TextTrack.prototype.addCue = function addCue(cue) { var tracks = this.tech_.textTracks(); if (tracks) { for (var i = 0; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } } this.cues_.push(cue); this.cues.setCues_(this.cues_); }; /** * remvoe a cue from our internal list * * @param {Object} removeCue the cue to remove from our internal list * @method removeCue */ TextTrack.prototype.removeCue = function removeCue(_removeCue) { var removed = false; for (var i = 0, l = this.cues_.length; i < l; i++) { var cue = this.cues_[i]; if (cue === _removeCue) { this.cues_.splice(i, 1); removed = true; } } if (removed) { this.cues.setCues_(this.cues_); } }; return TextTrack; })(_eventTarget2['default']); TextTrack.prototype.allowedEvents_ = { cuechange: 'cuechange' }; exports['default'] = TextTrack; module.exports = exports['default']; },{"../event-target":99,"../utils/browser.js":129,"../utils/fn.js":134,"../utils/guid.js":136,"../utils/log.js":137,"../utils/url.js":142,"./text-track-cue-list":122,"./text-track-enums":124,"global/document":1,"global/window":2,"xhr":56}],129:[function(_dereq_,module,exports){ /** * @file browser.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var USER_AGENT = _globalWindow2['default'].navigator.userAgent; var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT); var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null; /* * Device is an iPhone * * @type {Boolean} * @constant * @private */ var IS_IPAD = /iPad/i.test(USER_AGENT); exports.IS_IPAD = IS_IPAD; // The Facebook app's UIWebView identifies as both an iPhone and iPad, so // to identify iPhones, we need to exclude iPads. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/ var IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD; exports.IS_IPHONE = IS_IPHONE; var IS_IPOD = /iPod/i.test(USER_AGENT); exports.IS_IPOD = IS_IPOD; var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; exports.IS_IOS = IS_IOS; var IOS_VERSION = (function () { var match = USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); exports.IOS_VERSION = IOS_VERSION; var IS_ANDROID = /Android/i.test(USER_AGENT); exports.IS_ANDROID = IS_ANDROID; var ANDROID_VERSION = (function () { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parseFloat(match[1]); minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); exports.ANDROID_VERSION = ANDROID_VERSION; // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser var IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3; exports.IS_OLD_ANDROID = IS_OLD_ANDROID; var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537; exports.IS_NATIVE_ANDROID = IS_NATIVE_ANDROID; var IS_FIREFOX = /Firefox/i.test(USER_AGENT); exports.IS_FIREFOX = IS_FIREFOX; var IS_CHROME = /Chrome/i.test(USER_AGENT); exports.IS_CHROME = IS_CHROME; var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT); exports.IS_IE8 = IS_IE8; var TOUCH_ENABLED = !!('ontouchstart' in _globalWindow2['default'] || _globalWindow2['default'].DocumentTouch && _globalDocument2['default'] instanceof _globalWindow2['default'].DocumentTouch); exports.TOUCH_ENABLED = TOUCH_ENABLED; var BACKGROUND_SIZE_SUPPORTED = ('backgroundSize' in _globalDocument2['default'].createElement('video').style); exports.BACKGROUND_SIZE_SUPPORTED = BACKGROUND_SIZE_SUPPORTED; },{"global/document":1,"global/window":2}],130:[function(_dereq_,module,exports){ /** * @file buffer.js */ 'use strict'; exports.__esModule = true; exports.bufferedPercent = bufferedPercent; var _timeRangesJs = _dereq_('./time-ranges.js'); /** * Compute how much your video has been buffered * * @param {Object} Buffered object * @param {Number} Total duration * @return {Number} Percent buffered of the total duration * @private * @function bufferedPercent */ function bufferedPercent(buffered, duration) { var bufferedDuration = 0, start, end; if (!duration) { return 0; } if (!buffered || !buffered.length) { buffered = _timeRangesJs.createTimeRange(0, 0); } for (var i = 0; i < buffered.length; i++) { start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; } },{"./time-ranges.js":140}],131:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _logJs = _dereq_('./log.js'); var _logJs2 = _interopRequireDefault(_logJs); /** * Object containing the default behaviors for available handler methods. * * @private * @type {Object} */ var defaultBehaviors = { get: function get(obj, key) { return obj[key]; }, set: function set(obj, key, value) { obj[key] = value; return true; } }; /** * Expose private objects publicly using a Proxy to log deprecation warnings. * * Browsers that do not support Proxy objects will simply return the `target` * object, so it can be directly exposed. * * @param {Object} target The target object. * @param {Object} messages Messages to display from a Proxy. Only operations * with an associated message will be proxied. * @param {String} [messages.get] * @param {String} [messages.set] * @return {Object} A Proxy if supported or the `target` argument. */ exports['default'] = function (target) { var messages = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; if (typeof Proxy === 'function') { var _ret = (function () { var handler = {}; // Build a handler object based on those keys that have both messages // and default behaviors. Object.keys(messages).forEach(function (key) { if (defaultBehaviors.hasOwnProperty(key)) { handler[key] = function () { _logJs2['default'].warn(messages[key]); return defaultBehaviors[key].apply(this, arguments); }; } }); return { v: new Proxy(target, handler) }; })(); if (typeof _ret === 'object') return _ret.v; } return target; }; module.exports = exports['default']; },{"./log.js":137}],132:[function(_dereq_,module,exports){ /** * @file dom.js */ 'use strict'; exports.__esModule = true; exports.getEl = getEl; exports.createEl = createEl; exports.textContent = textContent; exports.insertElFirst = insertElFirst; exports.getElData = getElData; exports.hasElData = hasElData; exports.removeElData = removeElData; exports.hasElClass = hasElClass; exports.addElClass = addElClass; exports.removeElClass = removeElClass; exports.toggleElClass = toggleElClass; exports.setElAttributes = setElAttributes; exports.getElAttributes = getElAttributes; exports.blockTextSelection = blockTextSelection; exports.unblockTextSelection = unblockTextSelection; exports.findElPosition = findElPosition; exports.getPointerPosition = getPointerPosition; exports.isEl = isEl; exports.isTextNode = isTextNode; exports.emptyEl = emptyEl; exports.normalizeContent = normalizeContent; exports.appendContent = appendContent; exports.insertContent = insertContent; var _templateObject = _taggedTemplateLiteralLoose(['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.'], ['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.']); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _guidJs = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_guidJs); var _logJs = _dereq_('./log.js'); var _logJs2 = _interopRequireDefault(_logJs); var _tsml = _dereq_('tsml'); var _tsml2 = _interopRequireDefault(_tsml); /** * Detect if a value is a string with any non-whitespace characters. * * @param {String} str * @return {Boolean} */ function isNonBlankString(str) { return typeof str === 'string' && /\S/.test(str); } /** * Throws an error if the passed string has whitespace. This is used by * class methods to be relatively consistent with the classList API. * * @param {String} str * @return {Boolean} */ function throwIfWhitespace(str) { if (/\s/.test(str)) { throw new Error('class has illegal whitespace characters'); } } /** * Produce a regular expression for matching a class name. * * @param {String} className * @return {RegExp} */ function classRegExp(className) { return new RegExp('(^|\\s)' + className + '($|\\s)'); } /** * Creates functions to query the DOM using a given method. * * @function createQuerier * @private * @param {String} method * @return {Function} */ function createQuerier(method) { return function (selector, context) { if (!isNonBlankString(selector)) { return _globalDocument2['default'][method](null); } if (isNonBlankString(context)) { context = _globalDocument2['default'].querySelector(context); } return (isEl(context) ? context : _globalDocument2['default'])[method](selector); }; } /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * * @param {String} id Element ID * @return {Element} Element with supplied ID * @function getEl */ function getEl(id) { if (id.indexOf('#') === 0) { id = id.slice(1); } return _globalDocument2['default'].getElementById(id); } /** * Creates an element and applies properties. * * @param {String} [tagName='div'] Name of tag to be created. * @param {Object} [properties={}] Element properties to be applied. * @param {Object} [attributes={}] Element attributes to be applied. * @return {Element} * @function createEl */ function createEl() { var tagName = arguments.length <= 0 || arguments[0] === undefined ? 'div' : arguments[0]; var properties = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var el = _globalDocument2['default'].createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // See #2176 // We originally were accepting both properties and attributes in the // same object, but that doesn't work so well. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') { _logJs2['default'].warn(_tsml2['default'](_templateObject, propName, val)); el.setAttribute(propName, val); } else { el[propName] = val; } }); Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var val = attributes[attrName]; el.setAttribute(attrName, attributes[attrName]); }); return el; } /** * Injects text into an element, replacing any existing contents entirely. * * @param {Element} el * @param {String} text * @return {Element} * @function textContent */ function textContent(el, text) { if (typeof el.textContent === 'undefined') { el.innerText = text; } else { el.textContent = text; } } /** * Insert an element as the first child node of another * * @param {Element} child Element to insert * @param {Element} parent Element to insert child into * @private * @function insertElFirst */ function insertElFirst(child, parent) { if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * * @type {Object} * @private */ var elData = {}; /* * Unique attribute name to store an element's guid in * * @type {String} * @constant * @private */ var elIdAttr = 'vdata' + new Date().getTime(); /** * Returns the cache object where data for an element is stored * * @param {Element} el Element to store data for. * @return {Object} * @function getElData */ function getElData(el) { var id = el[elIdAttr]; if (!id) { id = el[elIdAttr] = Guid.newGUID(); } if (!elData[id]) { elData[id] = {}; } return elData[id]; } /** * Returns whether or not an element has cached data * * @param {Element} el A dom element * @return {Boolean} * @private * @function hasElData */ function hasElData(el) { var id = el[elIdAttr]; if (!id) { return false; } return !!Object.getOwnPropertyNames(elData[id]).length; } /** * Delete data for the element from the cache and the guid attr from getElementById * * @param {Element} el Remove data for an element * @private * @function removeElData */ function removeElData(el) { var id = el[elIdAttr]; if (!id) { return; } // Remove all stored data delete elData[id]; // Remove the elIdAttr property from the DOM node try { delete el[elIdAttr]; } catch (e) { if (el.removeAttribute) { el.removeAttribute(elIdAttr); } else { // IE doesn't appear to support removeAttribute on the document element el[elIdAttr] = null; } } } /** * Check if an element has a CSS class * * @function hasElClass * @param {Element} element Element to check * @param {String} classToCheck Classname to check */ function hasElClass(element, classToCheck) { if (element.classList) { return element.classList.contains(classToCheck); } else { throwIfWhitespace(classToCheck); return classRegExp(classToCheck).test(element.className); } } /** * Add a CSS class name to an element * * @function addElClass * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add */ function addElClass(element, classToAdd) { if (element.classList) { element.classList.add(classToAdd); // Don't need to `throwIfWhitespace` here because `hasElClass` will do it // in the case of classList not being supported. } else if (!hasElClass(element, classToAdd)) { element.className = (element.className + ' ' + classToAdd).trim(); } return element; } /** * Remove a CSS class name from an element * * @function removeElClass * @param {Element} element Element to remove from class name * @param {String} classToRemove Classname to remove */ function removeElClass(element, classToRemove) { if (element.classList) { element.classList.remove(classToRemove); } else { throwIfWhitespace(classToRemove); element.className = element.className.split(/\s+/).filter(function (c) { return c !== classToRemove; }).join(' '); } return element; } /** * Adds or removes a CSS class name on an element depending on an optional * condition or the presence/absence of the class name. * * @function toggleElClass * @param {Element} element * @param {String} classToToggle * @param {Boolean|Function} [predicate] * Can be a function that returns a Boolean. If `true`, the class * will be added; if `false`, the class will be removed. If not * given, the class will be added if not present and vice versa. */ function toggleElClass(element, classToToggle, predicate) { // This CANNOT use `classList` internally because IE does not support the // second parameter to the `classList.toggle()` method! Which is fine because // `classList` will be used by the add/remove functions. var has = hasElClass(element, classToToggle); if (typeof predicate === 'function') { predicate = predicate(element, classToToggle); } if (typeof predicate !== 'boolean') { predicate = !has; } // If the necessary class operation matches the current state of the // element, no action is required. if (predicate === has) { return; } if (predicate) { addElClass(element, classToToggle); } else { removeElClass(element, classToToggle); } return element; } /** * Apply attributes to an HTML element. * * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. * @private * @function setElAttributes */ function setElAttributes(el, attributes) { Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var attrValue = attributes[attrName]; if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attrValue === true ? '' : attrValue); } }); } /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @param {Element} tag Element from which to get tag attributes * @return {Object} * @private * @function getElAttributes */ function getElAttributes(tag) { var obj, knownBooleans, attrs, attrName, attrVal; obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrName = attrs[i].name; attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = attrVal !== null ? true : false; } obj[attrName] = attrVal; } } return obj; } /** * Attempt to block the ability to select text while dragging controls * * @return {Boolean} * @function blockTextSelection */ function blockTextSelection() { _globalDocument2['default'].body.focus(); _globalDocument2['default'].onselectstart = function () { return false; }; } /** * Turn off text selection blocking * * @return {Boolean} * @function unblockTextSelection */ function unblockTextSelection() { _globalDocument2['default'].onselectstart = function () { return true; }; } /** * Offset Left * getBoundingClientRect technique from * John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ * * @function findElPosition * @param {Element} el Element from which to get offset * @return {Object} */ function findElPosition(el) { var box = undefined; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } var docEl = _globalDocument2['default'].documentElement; var body = _globalDocument2['default'].body; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollLeft = _globalWindow2['default'].pageXOffset || body.scrollLeft; var left = box.left + scrollLeft - clientLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var scrollTop = _globalWindow2['default'].pageYOffset || body.scrollTop; var top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: Math.round(left), top: Math.round(top) }; } /** * Get pointer position in element * Returns an object with x and y coordinates. * The base on the coordinates are the bottom left of the element. * * @function getPointerPosition * @param {Element} el Element on which to get the pointer position on * @param {Event} event Event object * @return {Object} This object will have x and y coordinates corresponding to the mouse position */ function getPointerPosition(el, event) { var position = {}; var box = findElPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; var boxY = box.top; var boxX = box.left; var pageY = event.pageY; var pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; } /** * Determines, via duck typing, whether or not a value is a DOM element. * * @function isEl * @param {Mixed} value * @return {Boolean} */ function isEl(value) { return !!value && typeof value === 'object' && value.nodeType === 1; } /** * Determines, via duck typing, whether or not a value is a text node. * * @param {Mixed} value * @return {Boolean} */ function isTextNode(value) { return !!value && typeof value === 'object' && value.nodeType === 3; } /** * Empties the contents of an element. * * @function emptyEl * @param {Element} el * @return {Element} */ function emptyEl(el) { while (el.firstChild) { el.removeChild(el.firstChild); } return el; } /** * Normalizes content for eventual insertion into the DOM. * * This allows a wide range of content definition methods, but protects * from falling into the trap of simply writing to `innerHTML`, which is * an XSS concern. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * - String * Normalized into a text node. * * - Element, TextNode * Passed through. * * - Array * A one-dimensional array of strings, elements, nodes, or functions (which * return single strings, elements, or nodes). * * - Function * If the sole argument, is expected to produce a string, element, * node, or array. * * @function normalizeContent * @param {String|Element|TextNode|Array|Function} content * @return {Array} */ function normalizeContent(content) { // First, invoke content if it is a function. If it produces an array, // that needs to happen before normalization. if (typeof content === 'function') { content = content(); } // Next up, normalize to an array, so one or many items can be normalized, // filtered, and returned. return (Array.isArray(content) ? content : [content]).map(function (value) { // First, invoke value if it is a function to produce a new value, // which will be subsequently normalized to a Node of some kind. if (typeof value === 'function') { value = value(); } if (isEl(value) || isTextNode(value)) { return value; } if (typeof value === 'string' && /\S/.test(value)) { return _globalDocument2['default'].createTextNode(value); } }).filter(function (value) { return value; }); } /** * Normalizes and appends content to an element. * * @function appendContent * @param {Element} el * @param {String|Element|TextNode|Array|Function} content * See: `normalizeContent` * @return {Element} */ function appendContent(el, content) { normalizeContent(content).forEach(function (node) { return el.appendChild(node); }); return el; } /** * Normalizes and inserts content into an element; this is identical to * `appendContent()`, except it empties the element first. * * @function insertContent * @param {Element} el * @param {String|Element|TextNode|Array|Function} content * See: `normalizeContent` * @return {Element} */ function insertContent(el, content) { return appendContent(emptyEl(el), content); } /** * Finds a single DOM element matching `selector` within the optional * `context` of another DOM element (defaulting to `document`). * * @function $ * @param {String} selector * A valid CSS selector, which will be passed to `querySelector`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {Element|null} */ var $ = createQuerier('querySelector'); exports.$ = $; /** * Finds a all DOM elements matching `selector` within the optional * `context` of another DOM element (defaulting to `document`). * * @function $$ * @param {String} selector * A valid CSS selector, which will be passed to `querySelectorAll`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {NodeList} */ var $$ = createQuerier('querySelectorAll'); exports.$$ = $$; },{"./guid.js":136,"./log.js":137,"global/document":1,"global/window":2,"tsml":55}],133:[function(_dereq_,module,exports){ /** * @file events.js * * Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. */ 'use strict'; exports.__esModule = true; exports.on = on; exports.off = off; exports.trigger = trigger; exports.one = one; exports.fixEvent = fixEvent; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } 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; } } var _domJs = _dereq_('./dom.js'); var Dom = _interopRequireWildcard(_domJs); var _guidJs = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_guidJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @method on */ function on(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(on, elem, type, fn); } var data = Dom.getElData(elem); // We need a place to store all our handler data if (!data.handlers) data.handlers = {}; if (!data.handlers[type]) data.handlers[type] = []; if (!fn.guid) fn.guid = Guid.newGUID(); data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event, hash) { if (data.disabled) return; event = fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { handlersCopy[m].call(elem, event, hash); } } } }; } if (data.handlers[type].length === 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } } /** * Removes event listeners from an element * * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @method off */ function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!Dom.hasElData(elem)) return; var data = Dom.getElData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(t) { data.handlers[t] = []; _cleanUpEvents(elem, t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) { removeType(t); }return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) return; // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); } /** * Trigger an event for an element * * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Boolean=} Returned only if default was prevented * @method trigger */ function trigger(elem, event, hash) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasElData first. var elemData = Dom.hasElData(elem) ? Dom.getElData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type: event, target: elem }; } // Normalizes the event properties. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event, hash); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles === true) { trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = Dom.getElData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; } /** * Trigger a listener only once for an event * * @param {Element|Object} elem Element or object to * @param {String|Array} type Name/type of event * @param {Function} fn Event handler function * @method one */ function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = function func() { off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || Guid.newGUID(); on(elem, type, func); } /** * Fix a native event to have standard property values * * @param {Object} event Event object to fix * @return {Object} * @private * @method fixEvent */ function fixEvent(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || _globalWindow2['default'].event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation // and webkitMovementX/Y if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key === 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || _globalDocument2['default']; } // Handle which other element the event is related to if (!event.relatedTarget) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; old.returnValue = false; event.defaultPrevented = true; }; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; old.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX != null) { var doc = _globalDocument2['default'].documentElement, body = _globalDocument2['default'].body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button != null) { event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0; } } // Returns fixed-up instance return event; } /** * Clean up the listener cache and dispatchers * * @param {Element|Object} elem Element to clean up * @param {String} type Type of event to clean up * @private * @method _cleanUpEvents */ function _cleanUpEvents(elem, type) { var data = Dom.getElData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (Object.getOwnPropertyNames(data.handlers).length <= 0) { delete data.handlers; delete data.dispatcher; delete data.disabled; } // Finally remove the element data if there is no data left if (Object.getOwnPropertyNames(data).length === 0) { Dom.removeElData(elem); } } /** * Loops through an array of event types and calls the requested method for each type. * * @param {Function} fn The event method we want to use. * @param {Element|Object} elem Element or object to bind listeners to * @param {String} type Type of event to bind to. * @param {Function} callback Event listener. * @private * @function _handleMultipleEvents */ function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { //Call the event method for each one of the types fn(elem, type, callback); }); } },{"./dom.js":132,"./guid.js":136,"global/document":1,"global/window":2}],134:[function(_dereq_,module,exports){ /** * @file fn.js */ 'use strict'; exports.__esModule = true; var _guidJs = _dereq_('./guid.js'); /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function * It also stores a unique id on the function so it can be easily removed from events * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} * @private * @method bind */ var bind = function bind(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = _guidJs.newGUID(); } // Create the new function that changes the context var ret = function ret() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks ret.guid = uid ? uid + '_' + fn.guid : fn.guid; return ret; }; exports.bind = bind; },{"./guid.js":136}],135:[function(_dereq_,module,exports){ /** * @file format-time.js * * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @private * @function formatTime */ 'use strict'; exports.__esModule = true; function formatTime(seconds) { var guide = arguments.length <= 1 || arguments[1] === undefined ? seconds : arguments[1]; return (function () { seconds = seconds < 0 ? 0 : seconds; var s = Math.floor(seconds % 60); var m = Math.floor(seconds / 60 % 60); var h = Math.floor(seconds / 3600); var gm = Math.floor(guide / 60 % 60); var gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = s < 10 ? '0' + s : s; return h + m + s; })(); } exports['default'] = formatTime; module.exports = exports['default']; },{}],136:[function(_dereq_,module,exports){ /** * @file guid.js * * Unique ID for an element or function * @type {Number} * @private */ "use strict"; exports.__esModule = true; exports.newGUID = newGUID; var _guid = 1; /** * Get the next unique ID * * @return {String} * @function newGUID */ function newGUID() { return _guid++; } },{}],137:[function(_dereq_,module,exports){ /** * @file log.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * Log plain debug messages */ var log = function log() { _logType(null, arguments); }; /** * Keep a history of log messages * @type {Array} */ log.history = []; /** * Log error messages */ log.error = function () { _logType('error', arguments); }; /** * Log warning messages */ log.warn = function () { _logType('warn', arguments); }; /** * Log messages to the console and history based on the type of message * * @param {String} type The type of message, or `null` for `log` * @param {Object} args The args to be passed to the log * @private * @method _logType */ function _logType(type, args) { // convert args to an array to get array functions var argsArray = Array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in log.history // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist var noop = function noop() {}; var console = _globalWindow2['default']['console'] || { 'log': noop, 'warn': noop, 'error': noop }; if (type) { // add the type to the front of the message argsArray.unshift(type.toUpperCase() + ':'); } else { // default to log with no prefix type = 'log'; } // add to history log.history.push(argsArray); // add console prefix after adding to history argsArray.unshift('VIDEOJS:'); // call appropriate log function if (console[type].apply) { console[type].apply(console, argsArray); } else { // ie8 doesn't allow error.apply, but it will just join() the array anyway console[type](argsArray.join(' ')); } } exports['default'] = log; module.exports = exports['default']; },{"global/window":2}],138:[function(_dereq_,module,exports){ /** * @file merge-options.js */ 'use strict'; exports.__esModule = true; exports['default'] = mergeOptions; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge'); var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge); function isPlain(obj) { return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; } /** * Merge customizer. video.js simply overwrites non-simple objects * (like arrays) instead of attempting to overlay them. * @see https://lodash.com/docs#merge */ var customizer = function customizer(destination, source) { // If we're not working with a plain object, copy the value as is // If source is an array, for instance, it will replace destination if (!isPlain(source)) { return source; } // If the new value is a plain object but the first object value is not // we need to create a new object for the first object to merge with. // This makes it consistent with how merge() works by default // and also protects from later changes the to first object affecting // the second object's values. if (!isPlain(destination)) { return mergeOptions(source); } }; /** * Merge one or more options objects, recursively merging **only** * plain object properties. Previously `deepMerge`. * * @param {...Object} source One or more objects to merge * @returns {Object} a new object that is the union of all * provided objects * @function mergeOptions */ function mergeOptions() { // contruct the call dynamically to handle the variable number of // objects to merge var args = Array.prototype.slice.call(arguments); // unshift an empty object into the front of the call as the target // of the merge args.unshift({}); // customize conflict resolution to match our historical merge behavior args.push(customizer); _lodashCompatObjectMerge2['default'].apply(null, args); // return the mutated result object return args[0]; } module.exports = exports['default']; },{"lodash-compat/object/merge":40}],139:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var createStyleElement = function createStyleElement(className) { var style = _globalDocument2['default'].createElement('style'); style.className = className; return style; }; exports.createStyleElement = createStyleElement; var setTextContent = function setTextContent(el, content) { if (el.styleSheet) { el.styleSheet.cssText = content; } else { el.textContent = content; } }; exports.setTextContent = setTextContent; },{"global/document":1}],140:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.createTimeRanges = createTimeRanges; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _logJs = _dereq_('./log.js'); var _logJs2 = _interopRequireDefault(_logJs); /** * @file time-ranges.js * * Should create a fake TimeRange object * Mimics an HTML5 time range instance, which has functions that * return the start and end times for a range * TimeRanges are returned by the buffered() method * * @param {(Number|Array)} Start of a single range or an array of ranges * @param {Number} End of a single range * @private * @method createTimeRanges */ function createTimeRanges(start, end) { if (Array.isArray(start)) { return createTimeRangesObj(start); } else if (start === undefined || end === undefined) { return createTimeRangesObj(); } return createTimeRangesObj([[start, end]]); } exports.createTimeRange = createTimeRanges; function createTimeRangesObj(ranges) { if (ranges === undefined || ranges.length === 0) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: ranges.length, start: getRange.bind(null, 'start', 0, ranges), end: getRange.bind(null, 'end', 1, ranges) }; } function getRange(fnName, valueIndex, ranges, rangeIndex) { if (rangeIndex === undefined) { _logJs2['default'].warn('DEPRECATED: Function \'' + fnName + '\' on \'TimeRanges\' called without an index argument.'); rangeIndex = 0; } rangeCheck(fnName, rangeIndex, ranges.length - 1); return ranges[rangeIndex][valueIndex]; } function rangeCheck(fnName, index, maxIndex) { if (index < 0 || index > maxIndex) { throw new Error('Failed to execute \'' + fnName + '\' on \'TimeRanges\': The index provided (' + index + ') is greater than or equal to the maximum bound (' + maxIndex + ').'); } } },{"./log.js":137}],141:[function(_dereq_,module,exports){ /** * @file to-title-case.js * * Uppercase the first letter of a string * * @param {String} string String to be uppercased * @return {String} * @private * @method toTitleCase */ "use strict"; exports.__esModule = true; function toTitleCase(string) { return string.charAt(0).toUpperCase() + string.slice(1); } exports["default"] = toTitleCase; module.exports = exports["default"]; },{}],142:[function(_dereq_,module,exports){ /** * @file url.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ var parseUrl = function parseUrl(url) { var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL var a = _globalDocument2['default'].createElement('a'); a.href = url; // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing var addToBody = a.host === '' && a.protocol !== 'file:'; var div = undefined; if (addToBody) { div = _globalDocument2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); _globalDocument2['default'].body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom var details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (addToBody) { _globalDocument2['default'].body.removeChild(div); } return details; }; exports.parseUrl = parseUrl; /** * Get absolute version of relative URL. Used to tell flash correct URL. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * * @param {String} url URL to make absolute * @return {String} Absolute URL * @private * @method getAbsoluteURL */ var getAbsoluteURL = function getAbsoluteURL(url) { // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. var div = _globalDocument2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '">x</a>'; url = div.firstChild.href; } return url; }; exports.getAbsoluteURL = getAbsoluteURL; /** * Returns the extension of the passed file name. It will return an empty string if you pass an invalid path * * @param {String} path The fileName path like '/path/to/file.mp4' * @returns {String} The extension in lower case or an empty string if no extension could be found. * @method getFileExtension */ var getFileExtension = function getFileExtension(path) { if (typeof path === 'string') { var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i; var pathParts = splitPathRe.exec(path); if (pathParts) { return pathParts.pop().toLowerCase(); } } return ''; }; exports.getFileExtension = getFileExtension; /** * Returns whether the url passed is a cross domain request or not. * * @param {String} url The url to check * @return {Boolean} Whether it is a cross domain request or not * @method isCrossOrigin */ var isCrossOrigin = function isCrossOrigin(url) { var winLoc = _globalWindow2['default'].location; var urlInfo = parseUrl(url); // IE8 protocol relative urls will return ':' for protocol var srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here var crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host; return crossOrigin; }; exports.isCrossOrigin = isCrossOrigin; },{"global/document":1,"global/window":2}],143:[function(_dereq_,module,exports){ /** * @file video.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _setup = _dereq_('./setup'); var setup = _interopRequireWildcard(_setup); var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js'); var stylesheet = _interopRequireWildcard(_utilsStylesheetJs); var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _eventTarget = _dereq_('./event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _player = _dereq_('./player'); var _player2 = _interopRequireDefault(_player); var _pluginsJs = _dereq_('./plugins.js'); var _pluginsJs2 = _interopRequireDefault(_pluginsJs); var _srcJsUtilsMergeOptionsJs = _dereq_('../../src/js/utils/merge-options.js'); var _srcJsUtilsMergeOptionsJs2 = _interopRequireDefault(_srcJsUtilsMergeOptionsJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _tracksTextTrackJs = _dereq_('./tracks/text-track.js'); var _tracksTextTrackJs2 = _interopRequireDefault(_tracksTextTrackJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js'); var _utilsFormatTimeJs = _dereq_('./utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _utilsUrlJs = _dereq_('./utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _extendJs = _dereq_('./extend.js'); var _extendJs2 = _interopRequireDefault(_extendJs); var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge'); var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge); var _utilsCreateDeprecationProxyJs = _dereq_('./utils/create-deprecation-proxy.js'); var _utilsCreateDeprecationProxyJs2 = _interopRequireDefault(_utilsCreateDeprecationProxyJs); var _xhr = _dereq_('xhr'); var _xhr2 = _interopRequireDefault(_xhr); // Include the built-in techs var _techTechJs = _dereq_('./tech/tech.js'); var _techTechJs2 = _interopRequireDefault(_techTechJs); var _techHtml5Js = _dereq_('./tech/html5.js'); var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js); var _techFlashJs = _dereq_('./tech/flash.js'); var _techFlashJs2 = _interopRequireDefault(_techFlashJs); // HTML5 Element Shim for IE8 if (typeof HTMLVideoElement === 'undefined') { _globalDocument2['default'].createElement('video'); _globalDocument2['default'].createElement('audio'); _globalDocument2['default'].createElement('track'); } /** * Doubles as the main function for users to create a player instance and also * the main library object. * The `videojs` function can be used to initialize or retrieve a player. * ```js * var myPlayer = videojs('my_video_id'); * ``` * * @param {String|Element} id Video element or video element ID * @param {Object=} options Optional options object for config/settings * @param {Function=} ready Optional ready callback * @return {Player} A player instance * @mixes videojs * @method videojs */ var videojs = function videojs(id, options, ready) { var tag = undefined; // Element of ID // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (videojs.getPlayers()[id]) { // If options or ready funtion are passed, warn if (options) { _utilsLogJs2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { videojs.getPlayers()[id].ready(ready); } return videojs.getPlayers()[id]; // Otherwise get element for ID } else { tag = Dom.getEl(id); } // ID is a media element } else { tag = id; } // Check for a useable element if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns } // Element may have a player attr referring to an already created player instance. // If not, set up a new player and return the instance. return tag['player'] || _player2['default'].players[tag.playerId] || new _player2['default'](tag, options, ready); }; // Add default styles var style = Dom.$('.vjs-styles-defaults'); if (!style) { style = stylesheet.createStyleElement('vjs-styles-defaults'); var head = Dom.$('head'); head.insertBefore(style, head.firstChild); stylesheet.setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid {\n padding-top: 56.25%\n }\n '); } // Run Auto-load players // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version) setup.autoSetupTimeout(1, videojs); /* * Current software version (semver) * * @type {String} */ videojs.VERSION = '5.8.6'; /** * The global options object. These are the settings that take effect * if no overrides are specified when the player is created. * * ```js * videojs.options.autoplay = true * // -> all players will autoplay by default * ``` * * @type {Object} */ videojs.options = _player2['default'].prototype.options_; /** * Get an object with the currently created players, keyed by player ID * * @return {Object} The created players * @mixes videojs * @method getPlayers */ videojs.getPlayers = function () { return _player2['default'].players; }; /** * For backward compatibility, expose players object. * * @deprecated * @memberOf videojs * @property {Object|Proxy} players */ videojs.players = _utilsCreateDeprecationProxyJs2['default'](_player2['default'].players, { get: 'Access to videojs.players is deprecated; use videojs.getPlayers instead', set: 'Modification of videojs.players is deprecated' }); /** * Get a component class object by name * ```js * var VjsButton = videojs.getComponent('Button'); * // Create a new instance of the component * var myButton = new VjsButton(myPlayer); * ``` * * @return {Component} Component identified by name * @mixes videojs * @method getComponent */ videojs.getComponent = _component2['default'].getComponent; /** * Register a component so it can referred to by name * Used when adding to other * components, either through addChild * `component.addChild('myComponent')` * or through default children options * `{ children: ['myComponent'] }`. * ```js * // Get a component to subclass * var VjsButton = videojs.getComponent('Button'); * // Subclass the component (see 'extend' doc for more info) * var MySpecialButton = videojs.extend(VjsButton, {}); * // Register the new component * VjsButton.registerComponent('MySepcialButton', MySepcialButton); * // (optionally) add the new component as a default player child * myPlayer.addChild('MySepcialButton'); * ``` * NOTE: You could also just initialize the component before adding. * `component.addChild(new MyComponent());` * * @param {String} The class name of the component * @param {Component} The component class * @return {Component} The newly registered component * @mixes videojs * @method registerComponent */ videojs.registerComponent = function (name, comp) { if (_techTechJs2['default'].isTech(comp)) { _utilsLogJs2['default'].warn('The ' + name + ' tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)'); } _component2['default'].registerComponent.call(_component2['default'], name, comp); }; /** * Get a Tech class object by name * ```js * var Html5 = videojs.getTech('Html5'); * // Create a new instance of the component * var html5 = new Html5(options); * ``` * * @return {Tech} Tech identified by name * @mixes videojs * @method getComponent */ videojs.getTech = _techTechJs2['default'].getTech; /** * Register a Tech so it can referred to by name. * This is used in the tech order for the player. * * ```js * // get the Html5 Tech * var Html5 = videojs.getTech('Html5'); * var MyTech = videojs.extend(Html5, {}); * // Register the new Tech * VjsButton.registerTech('Tech', MyTech); * var player = videojs('myplayer', { * techOrder: ['myTech', 'html5'] * }); * ``` * * @param {String} The class name of the tech * @param {Tech} The tech class * @return {Tech} The newly registered Tech * @mixes videojs * @method registerTech */ videojs.registerTech = _techTechJs2['default'].registerTech; /** * A suite of browser and device tests * * @type {Object} * @private */ videojs.browser = browser; /** * Whether or not the browser supports touch events. Included for backward * compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED` * instead going forward. * * @deprecated * @type {Boolean} */ videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED; /** * Subclass an existing class * Mimics ES6 subclassing with the `extend` keyword * ```js * // Create a basic javascript 'class' * function MyClass(name){ * // Set a property at initialization * this.myName = name; * } * // Create an instance method * MyClass.prototype.sayMyName = function(){ * alert(this.myName); * }; * // Subclass the exisitng class and change the name * // when initializing * var MySubClass = videojs.extend(MyClass, { * constructor: function(name) { * // Call the super class constructor for the subclass * MyClass.call(this, name) * } * }); * // Create an instance of the new sub class * var myInstance = new MySubClass('John'); * myInstance.sayMyName(); // -> should alert "John" * ``` * * @param {Function} The Class to subclass * @param {Object} An object including instace methods for the new class * Optionally including a `constructor` function * @return {Function} The newly created subclass * @mixes videojs * @method extend */ videojs.extend = _extendJs2['default']; /** * Merge two options objects recursively * Performs a deep merge like lodash.merge but **only merges plain objects** * (not arrays, elements, anything else) * Other values will be copied directly from the second object. * ```js * var defaultOptions = { * foo: true, * bar: { * a: true, * b: [1,2,3] * } * }; * var newOptions = { * foo: false, * bar: { * b: [4,5,6] * } * }; * var result = videojs.mergeOptions(defaultOptions, newOptions); * // result.foo = false; * // result.bar.a = true; * // result.bar.b = [4,5,6]; * ``` * * @param {Object} defaults The options object whose values will be overriden * @param {Object} overrides The options object with values to override the first * @param {Object} etc Any number of additional options objects * * @return {Object} a new object with the merged values * @mixes videojs * @method mergeOptions */ videojs.mergeOptions = _srcJsUtilsMergeOptionsJs2['default']; /** * Change the context (this) of a function * * videojs.bind(newContext, function(){ * this === newContext * }); * * NOTE: as of v5.0 we require an ES5 shim, so you should use the native * `function(){}.bind(newContext);` instead of this. * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} */ videojs.bind = Fn.bind; /** * Create a Video.js player plugin * Plugins are only initialized when options for the plugin are included * in the player options, or the plugin function on the player instance is * called. * **See the plugin guide in the docs for a more detailed example** * ```js * // Make a plugin that alerts when the player plays * videojs.plugin('myPlugin', function(myPluginOptions) { * myPluginOptions = myPluginOptions || {}; * * var player = this; * var alertText = myPluginOptions.text || 'Player is playing!' * * player.on('play', function(){ * alert(alertText); * }); * }); * // USAGE EXAMPLES * // EXAMPLE 1: New player with plugin options, call plugin immediately * var player1 = videojs('idOne', { * myPlugin: { * text: 'Custom text!' * } * }); * // Click play * // --> Should alert 'Custom text!' * // EXAMPLE 3: New player, initialize plugin later * var player3 = videojs('idThree'); * // Click play * // --> NO ALERT * // Click pause * // Initialize plugin using the plugin function on the player instance * player3.myPlugin({ * text: 'Plugin added later!' * }); * // Click play * // --> Should alert 'Plugin added later!' * ``` * * @param {String} name The plugin name * @param {Function} fn The plugin function that will be called with options * @mixes videojs * @method plugin */ videojs.plugin = _pluginsJs2['default']; /** * Adding languages so that they're available to all players. * ```js * videojs.addLanguage('es', { 'Hello': 'Hola' }); * ``` * * @param {String} code The language code or dictionary property * @param {Object} data The data values to be translated * @return {Object} The resulting language dictionary object * @mixes videojs * @method addLanguage */ videojs.addLanguage = function (code, data) { var _merge; code = ('' + code).toLowerCase(); return _lodashCompatObjectMerge2['default'](videojs.options.languages, (_merge = {}, _merge[code] = data, _merge))[code]; }; /** * Log debug messages. * * @param {...Object} messages One or more messages to log */ videojs.log = _utilsLogJs2['default']; /** * Creates an emulated TimeRange object. * * @param {Number|Array} start Start time in seconds or an array of ranges * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @method createTimeRange */ videojs.createTimeRange = videojs.createTimeRanges = _utilsTimeRangesJs.createTimeRanges; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @method formatTime */ videojs.formatTime = _utilsFormatTimeJs2['default']; /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ videojs.parseUrl = Url.parseUrl; /** * Returns whether the url passed is a cross domain request or not. * * @param {String} url The url to check * @return {Boolean} Whether it is a cross domain request or not * @method isCrossOrigin */ videojs.isCrossOrigin = Url.isCrossOrigin; /** * Event target class. * * @type {Function} */ videojs.EventTarget = _eventTarget2['default']; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @method on */ videojs.on = Events.on; /** * Trigger a listener only once for an event * * @param {Element|Object} elem Element or object to * @param {String|Array} type Name/type of event * @param {Function} fn Event handler function * @method one */ videojs.one = Events.one; /** * Removes event listeners from an element * * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @method off */ videojs.off = Events.off; /** * Trigger an event for an element * * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Boolean=} Returned only if default was prevented * @method trigger */ videojs.trigger = Events.trigger; /** * A cross-browser XMLHttpRequest wrapper. Here's a simple example: * * videojs.xhr({ * body: someJSONString, * uri: "/foo", * headers: { * "Content-Type": "application/json" * } * }, function (err, resp, body) { * // check resp.statusCode * }); * * Check out the [full * documentation](https://github.com/Raynos/xhr/blob/v2.1.0/README.md) * for more options. * * @param {Object} options settings for the request. * @return {XMLHttpRequest|XDomainRequest} the request object. * @see https://github.com/Raynos/xhr */ videojs.xhr = _xhr2['default']; /** * TextTrack class * * @type {Function} */ videojs.TextTrack = _tracksTextTrackJs2['default']; /** * Determines, via duck typing, whether or not a value is a DOM element. * * @method isEl * @param {Mixed} value * @return {Boolean} */ videojs.isEl = Dom.isEl; /** * Determines, via duck typing, whether or not a value is a text node. * * @method isTextNode * @param {Mixed} value * @return {Boolean} */ videojs.isTextNode = Dom.isTextNode; /** * Creates an element and applies properties. * * @method createEl * @param {String} [tagName='div'] Name of tag to be created. * @param {Object} [properties={}] Element properties to be applied. * @param {Object} [attributes={}] Element attributes to be applied. * @return {Element} */ videojs.createEl = Dom.createEl; /** * Check if an element has a CSS class * * @method hasClass * @param {Element} element Element to check * @param {String} classToCheck Classname to check */ videojs.hasClass = Dom.hasElClass; /** * Add a CSS class name to an element * * @method addClass * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add */ videojs.addClass = Dom.addElClass; /** * Remove a CSS class name from an element * * @method removeClass * @param {Element} element Element to remove from class name * @param {String} classToRemove Classname to remove */ videojs.removeClass = Dom.removeElClass; /** * Adds or removes a CSS class name on an element depending on an optional * condition or the presence/absence of the class name. * * @method toggleElClass * @param {Element} element * @param {String} classToToggle * @param {Boolean|Function} [predicate] * Can be a function that returns a Boolean. If `true`, the class * will be added; if `false`, the class will be removed. If not * given, the class will be added if not present and vice versa. */ videojs.toggleClass = Dom.toggleElClass; /** * Apply attributes to an HTML element. * * @method setAttributes * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. */ videojs.setAttributes = Dom.setElAttributes; /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @method getAttributes * @param {Element} tag Element from which to get tag attributes * @return {Object} */ videojs.getAttributes = Dom.getElAttributes; /** * Empties the contents of an element. * * @method emptyEl * @param {Element} el * @return {Element} */ videojs.emptyEl = Dom.emptyEl; /** * Normalizes and appends content to an element. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * - String * Normalized into a text node. * * - Element, TextNode * Passed through. * * - Array * A one-dimensional array of strings, elements, nodes, or functions (which * return single strings, elements, or nodes). * * - Function * If the sole argument, is expected to produce a string, element, * node, or array. * * @method appendContent * @param {Element} el * @param {String|Element|TextNode|Array|Function} content * @return {Element} */ videojs.appendContent = Dom.appendContent; /** * Normalizes and inserts content into an element; this is identical to * `appendContent()`, except it empties the element first. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * - String * Normalized into a text node. * * - Element, TextNode * Passed through. * * - Array * A one-dimensional array of strings, elements, nodes, or functions (which * return single strings, elements, or nodes). * * - Function * If the sole argument, is expected to produce a string, element, * node, or array. * * @method insertContent * @param {Element} el * @param {String|Element|TextNode|Array|Function} content * @return {Element} */ videojs.insertContent = Dom.insertContent; /* * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define['amd']) { define('videojs', [], function () { return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module['exports'] = videojs; } exports['default'] = videojs; module.exports = exports['default']; },{"../../src/js/utils/merge-options.js":138,"./component":67,"./event-target":99,"./extend.js":100,"./player":108,"./plugins.js":109,"./setup":113,"./tech/flash.js":116,"./tech/html5.js":117,"./tech/tech.js":119,"./tracks/text-track.js":128,"./utils/browser.js":129,"./utils/create-deprecation-proxy.js":131,"./utils/dom.js":132,"./utils/events.js":133,"./utils/fn.js":134,"./utils/format-time.js":135,"./utils/log.js":137,"./utils/stylesheet.js":139,"./utils/time-ranges.js":140,"./utils/url.js":142,"global/document":1,"lodash-compat/object/merge":40,"object.assign":45,"xhr":56}]},{},[143])(143) }); //# sourceMappingURL=video.js.map
node_modules/reactify/node_modules/react-tools/src/utils/__tests__/cloneWithProps-test.js
SteveDugas/react-dropdown
/** * 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. * * @emails react-core * @jsx React.DOM */ "use strict"; require('mock-modules') .dontMock('cloneWithProps') .dontMock('emptyObject'); var mocks = require('mocks'); var React; var ReactTestUtils; var onlyChild; var cloneWithProps; var emptyObject; describe('cloneWithProps', function() { beforeEach(function() { React = require('React'); ReactTestUtils = require('ReactTestUtils'); onlyChild = require('onlyChild'); cloneWithProps = require('cloneWithProps'); emptyObject = require('emptyObject'); }); it('should clone a DOM component with new props', function() { var Grandparent = React.createClass({ render: function() { return <Parent><div className="child" /></Parent>; } }); var Parent = React.createClass({ render: function() { return ( <div className="parent"> {cloneWithProps(onlyChild(this.props.children), {className: 'xyz'})} </div> ); } }); var component = ReactTestUtils.renderIntoDocument(<Grandparent />); expect(component.getDOMNode().childNodes[0].className) .toBe('xyz child'); }); it('should clone a composite component with new props', function() { var Child = React.createClass({ render: function() { return <div className={this.props.className} />; } }); var Grandparent = React.createClass({ render: function() { return <Parent><Child className="child" /></Parent>; } }); var Parent = React.createClass({ render: function() { return ( <div className="parent"> {cloneWithProps(onlyChild(this.props.children), {className: 'xyz'})} </div> ); } }); var component = ReactTestUtils.renderIntoDocument(<Grandparent />); expect(component.getDOMNode().childNodes[0].className) .toBe('xyz child'); }); it('should warn when cloning with refs', function() { var Grandparent = React.createClass({ render: function() { return <Parent><div ref="yolo" /></Parent>; } }); var Parent = React.createClass({ render: function() { return ( <div> {cloneWithProps(onlyChild(this.props.children), {className: 'xyz'})} </div> ); } }); var _warn = console.warn; try { console.warn = mocks.getMockFunction(); var component = ReactTestUtils.renderIntoDocument(<Grandparent />); expect(component.refs).toBe(emptyObject); expect(console.warn.mock.calls.length).toBe(1); } finally { console.warn = _warn; } }); it('should transfer the key property', function() { var Component = React.createClass({ render: function() { expect(this.props.key).toBe('xyz'); return <div />; } }); ReactTestUtils.renderIntoDocument( cloneWithProps(<Component />, {key: 'xyz'}) ); }); it('should transfer children', function() { var Component = React.createClass({ render: function() { expect(this.props.children).toBe('xyz'); return <div />; } }); ReactTestUtils.renderIntoDocument( cloneWithProps(<Component />, {children: 'xyz'}) ); }); it('should shallow clone children', function() { var Component = React.createClass({ render: function() { expect(this.props.children).toBe('xyz'); return <div />; } }); ReactTestUtils.renderIntoDocument( cloneWithProps(<Component>xyz</Component>, {}) ); }); it('should support keys and refs', function() { var Component = React.createClass({ render: function() { expect(this.props.key).toBe('xyz'); expect(this.props.ref).toBe('xyz'); return <div />; } }); var Parent = React.createClass({ render: function() { var clone = cloneWithProps(this.props.children, {key: 'xyz', ref: 'xyz'}); return <div>{clone}</div>; } }); var Grandparent = React.createClass({ render: function() { return <Parent><Component key="abc" ref="abc" /></Parent>; } }); ReactTestUtils.renderIntoDocument(<Grandparent />); }); it('should overwrite props', function() { var Component = React.createClass({ render: function() { expect(this.props.myprop).toBe('xyz'); return <div />; } }); ReactTestUtils.renderIntoDocument( cloneWithProps(<Component myprop="abc" />, {myprop: 'xyz'}) ); }); });
test/auto_text_link.js
hokuma/auto-text-link
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import { expect } from 'chai'; import AutoTextLink from '../src/auto_text_link'; describe('AutoTextLink', () => { let text; let url; let renderer; beforeEach(() => { url = 'https://github.com/hokuma'; text = `Url ${url} Not Url`; renderer = TestUtils.createRenderer(); renderer.render( <AutoTextLink className='link' target='_blank'>{text}</AutoTextLink> ); }); it('renders url as text link', () => { let result = renderer.getRenderOutput(); let expectedProps = { key: 0, className: 'link', target: '_blank' }; expect(result.props.children).to.eql( ['Url ', <a {...expectedProps} href={url}>{url}</a>, ' Not Url'] ); }); });
ajax/libs/onsen/2.0.0-rc.6/js/angular-onsenui.js
cdnjs/cdnjs
/*! angular-onsenui.js for onsenui - v2.0.0-rc.6 - 2016-05-25 */ /* Simple JavaScript Inheritance * By John Resig http://ejohn.org/ * MIT Licensed. */ // Inspired by base2 and Prototype (function () { var initializing = false, fnTest = /xyz/.test(function () { xyz; }) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) this.Class = function () {}; // Create a new Class that inherits from this class Class.extend = function (prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var prototype = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? function (name, fn) { return function () { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; }(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if (!initializing && this.init) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = prototype; // Enforce the constructor to be what we expect Class.prototype.constructor = Class; // And make this class extendable Class.extend = arguments.callee; return Class; }; })(); //HEAD (function (app) { try { app = angular.module("templates-main"); } catch (err) { app = angular.module("templates-main", []); } app.run(["$templateCache", function ($templateCache) { "use strict"; $templateCache.put("templates/sliding_menu.tpl", "<div class=\"onsen-sliding-menu__menu ons-sliding-menu-inner\"></div>\n" + "<div class=\"onsen-sliding-menu__main ons-sliding-menu-inner\"></div>\n" + ""); $templateCache.put("templates/split_view.tpl", "<div class=\"onsen-split-view__secondary full-screen ons-split-view-inner\"></div>\n" + "<div class=\"onsen-split-view__main full-screen ons-split-view-inner\"></div>\n" + ""); }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ /** * @object ons * @description * [ja]Onsen UIで利用できるグローバルなオブジェクトです。このオブジェクトは、AngularJSのスコープから参照することができます。 [/ja] * [en]A global object that's used in Onsen UI. This object can be reached from the AngularJS scope.[/en] */ (function (ons) { 'use strict'; var module = angular.module('onsen', ['templates-main']); angular.module('onsen.directives', ['onsen']); // for BC // JS Global facade for Onsen UI. initOnsenFacade(); waitOnsenUILoad(); initAngularModule(); function waitOnsenUILoad() { var unlockOnsenUI = ons._readyLock.lock(); module.run(['$compile', '$rootScope', function ($compile, $rootScope) { // for initialization hook. if (document.readyState === 'loading' || document.readyState == 'uninitialized') { window.addEventListener('DOMContentLoaded', function () { document.body.appendChild(document.createElement('ons-dummy-for-init')); }); } else if (document.body) { document.body.appendChild(document.createElement('ons-dummy-for-init')); } else { throw new Error('Invalid initialization state.'); } $rootScope.$on('$ons-ready', unlockOnsenUI); }]); } function initAngularModule() { module.value('$onsGlobal', ons); module.run(['$compile', '$rootScope', '$onsen', '$q', function ($compile, $rootScope, $onsen, $q) { ons._onsenService = $onsen; ons._qService = $q; $rootScope.ons = window.ons; $rootScope.console = window.console; $rootScope.alert = window.alert; ons.$compile = $compile; }]); } function initOnsenFacade() { ons._onsenService = null; // Object to attach component variables to when using the var="..." attribute. // Can be set to null to avoid polluting the global scope. ons.componentBase = window; /** * @method bootstrap * @signature bootstrap([moduleName, [dependencies]]) * @description * [ja]Onsen UIの初期化を行います。Angular.jsのng-app属性を利用すること無しにOnsen UIを読み込んで初期化してくれます。[/ja] * [en]Initialize Onsen UI. Can be used to load Onsen UI without using the <code>ng-app</code> attribute from AngularJS.[/en] * @param {String} [moduleName] * [en]AngularJS module name.[/en] * [ja]Angular.jsでのモジュール名[/ja] * @param {Array} [dependencies] * [en]List of AngularJS module dependencies.[/en] * [ja]依存するAngular.jsのモジュール名の配列[/ja] * @return {Object} * [en]An AngularJS module object.[/en] * [ja]AngularJSのModuleオブジェクトを表します。[/ja] */ ons.bootstrap = function (name, deps) { if (angular.isArray(name)) { deps = name; name = undefined; } if (!name) { name = 'myOnsenApp'; } deps = ['onsen'].concat(angular.isArray(deps) ? deps : []); var module = angular.module(name, deps); var doc = window.document; if (doc.readyState == 'loading' || doc.readyState == 'uninitialized' || doc.readyState == 'interactive') { doc.addEventListener('DOMContentLoaded', function () { angular.bootstrap(doc.documentElement, [name]); }, false); } else if (doc.documentElement) { angular.bootstrap(doc.documentElement, [name]); } else { throw new Error('Invalid state'); } return module; }; /** * @method findParentComponentUntil * @signature findParentComponentUntil(name, [dom]) * @param {String} name * [en]Name of component, i.e. 'ons-page'.[/en] * [ja]コンポーネント名を指定します。例えばons-pageなどを指定します。[/ja] * @param {Object/jqLite/HTMLElement} [dom] * [en]$event, jqLite or HTMLElement object.[/en] * [ja]$eventオブジェクト、jqLiteオブジェクト、HTMLElementオブジェクトのいずれかを指定できます。[/ja] * @return {Object} * [en]Component object. Will return null if no component was found.[/en] * [ja]コンポーネントのオブジェクトを返します。もしコンポーネントが見つからなかった場合にはnullを返します。[/ja] * @description * [en]Find parent component object of <code>dom</code> element.[/en] * [ja]指定されたdom引数の親要素をたどってコンポーネントを検索します。[/ja] */ ons.findParentComponentUntil = function (name, dom) { var element; if (dom instanceof HTMLElement) { element = angular.element(dom); } else if (dom instanceof angular.element) { element = dom; } else if (dom.target) { element = angular.element(dom.target); } return element.inheritedData(name); }; /** * @method findComponent * @signature findComponent(selector, [dom]) * @param {String} selector * [en]CSS selector[/en] * [ja]CSSセレクターを指定します。[/ja] * @param {HTMLElement} [dom] * [en]DOM element to search from.[/en] * [ja]検索対象とするDOM要素を指定します。[/ja] * @return {Object/null} * [en]Component object. Will return null if no component was found.[/en] * [ja]コンポーネントのオブジェクトを返します。もしコンポーネントが見つからなかった場合にはnullを返します。[/ja] * @description * [en]Find component object using CSS selector.[/en] * [ja]CSSセレクタを使ってコンポーネントのオブジェクトを検索します。[/ja] */ ons.findComponent = function (selector, dom) { var target = (dom ? dom : document).querySelector(selector); return target ? angular.element(target).data(target.nodeName.toLowerCase()) || null : null; }; /** * @method compile * @signature compile(dom) * @param {HTMLElement} dom * [en]Element to compile.[/en] * [ja]コンパイルする要素を指定します。[/ja] * @description * [en]Compile Onsen UI components.[/en] * [ja]通常のHTMLの要素をOnsen UIのコンポーネントにコンパイルします。[/ja] */ ons.compile = function (dom) { if (!ons.$compile) { throw new Error('ons.$compile() is not ready. Wait for initialization with ons.ready().'); } if (!(dom instanceof HTMLElement)) { throw new Error('First argument must be an instance of HTMLElement.'); } var scope = angular.element(dom).scope(); if (!scope) { throw new Error('AngularJS Scope is null. Argument DOM element must be attached in DOM document.'); } ons.$compile(dom)(scope); }; ons._getOnsenService = function () { if (!this._onsenService) { throw new Error('$onsen is not loaded, wait for ons.ready().'); } return this._onsenService; }; /** * @param {String} elementName * @param {Function} lastReady * @return {Function} */ ons._waitDiretiveInit = function (elementName, lastReady) { return function (element, callback) { if (angular.element(element).data(elementName)) { lastReady(element, callback); } else { var listen = function listen() { lastReady(element, callback); element.removeEventListener(elementName + ':init', listen, false); }; element.addEventListener(elementName + ':init', listen, false); } }; }; /** * @method createAlertDialog * @signature createAlertDialog(page, [options]) * @param {String} page * [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-alert-dialog> component.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Object} [options.parentScope] * [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en] * [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。このパラメータはAngularJSバインディングでのみ利用できます。[/ja] * @return {Promise} * [en]Promise object that resolves to the alert dialog component object.[/en] * [ja]ダイアログのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja] * @description * [en]Create a alert dialog instance from a template.[/en] * [ja]テンプレートからアラートダイアログのインスタンスを生成します。[/ja] */ ons.createAlertDialog = function (page, options) { options = options || {}; options.link = function (element) { if (options.parentScope) { ons.$compile(angular.element(element))(options.parentScope.$new()); } else { ons.compile(element); } }; return ons._createAlertDialogOriginal(page, options).then(function (alertDialog) { return angular.element(alertDialog).data('ons-alert-dialog'); }); }; /** * @method createDialog * @signature createDialog(page, [options]) * @param {String} page * [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-dialog> component.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Object} [options.parentScope] * [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en] * [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。このパラメータはAngularJSバインディングでのみ利用できます。[/ja] * @return {Promise} * [en]Promise object that resolves to the dialog component object.[/en] * [ja]ダイアログのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja] * @description * [en]Create a dialog instance from a template.[/en] * [ja]テンプレートからダイアログのインスタンスを生成します。[/ja] */ ons.createDialog = function (page, options) { options = options || {}; options.link = function (element) { if (options.parentScope) { ons.$compile(angular.element(element))(options.parentScope.$new()); } else { ons.compile(element); } }; return ons._createDialogOriginal(page, options).then(function (dialog) { return angular.element(dialog).data('ons-dialog'); }); }; /** * @method createPopover * @signature createPopover(page, [options]) * @param {String} page * [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-dialog> component.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Object} [options.parentScope] * [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en] * [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。このパラメータはAngularJSバインディングでのみ利用できます。[/ja] * @return {Promise} * [en]Promise object that resolves to the popover component object.[/en] * [ja]ポップオーバーのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja] * @description * [en]Create a popover instance from a template.[/en] * [ja]テンプレートからポップオーバーのインスタンスを生成します。[/ja] */ ons.createPopover = function (page, options) { options = options || {}; options.link = function (element) { if (options.parentScope) { ons.$compile(angular.element(element))(options.parentScope.$new()); } else { ons.compile(element); } }; return ons._createPopoverOriginal(page, options).then(function (popover) { return angular.element(popover).data('ons-popover'); }); }; /** * @param {String} page */ ons.resolveLoadingPlaceholder = function (page) { return ons._resolveLoadingPlaceholderOriginal(page, function (element, done) { ons.compile(element); angular.element(element).scope().$evalAsync(function () { setImmediate(done); }); }); }; ons._setupLoadingPlaceHolders = function () { // Do nothing }; } })(window.ons = window.ons || {}); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('AlertDialogView', ['$onsen', function ($onsen) { var AlertDialogView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function init(scope, element, attrs) { this._scope = scope; this._element = element; this._attrs = attrs; this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], ['show', 'hide']); this._clearDerivingEvents = $onsen.deriveEvents(this, this._element[0], ['preshow', 'postshow', 'prehide', 'posthide', 'cancel'], function (detail) { if (detail.alertDialog) { detail.alertDialog = this; } return detail; }.bind(this)); this._scope.$on('$destroy', this._destroy.bind(this)); }, _destroy: function _destroy() { this.emit('destroy'); this._element.remove(); this._clearDerivingMethods(); this._clearDerivingEvents(); this._scope = this._attrs = this._element = null; } }); MicroEvent.mixin(AlertDialogView); $onsen.derivePropertiesFromElement(AlertDialogView, ['disabled', 'cancelable', 'visible', 'onDeviceBackButton']); return AlertDialogView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ angular.module('onsen').value('AlertDialogAnimator', ons._internal.AlertDialogAnimator).value('AndroidAlertDialogAnimator', ons._internal.AndroidAlertDialogAnimator).value('IOSAlertDialogAnimator', ons._internal.IOSAlertDialogAnimator); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ angular.module('onsen').value('AnimationChooser', ons._internal.AnimatorFactory); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('CarouselView', ['$onsen', function ($onsen) { /** * @class CarouselView */ var CarouselView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function init(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingMethods = $onsen.deriveMethods(this, element[0], ['setActiveIndex', 'getActiveIndex', 'next', 'prev', 'refresh', 'first', 'last']); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['refresh', 'postchange', 'overscroll'], function (detail) { if (detail.carousel) { detail.carousel = this; } return detail; }.bind(this)); }, _destroy: function _destroy() { this.emit('destroy'); this._clearDerivingEvents(); this._clearDerivingMethods(); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(CarouselView); $onsen.derivePropertiesFromElement(CarouselView, ['centered', 'overscrollable', 'disabled', 'autoScroll', 'swipeable', 'autoScrollRatio', 'itemCount']); return CarouselView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('DialogView', ['$onsen', function ($onsen) { var DialogView = Class.extend({ init: function init(scope, element, attrs) { this._scope = scope; this._element = element; this._attrs = attrs; this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], ['show', 'hide']); this._clearDerivingEvents = $onsen.deriveEvents(this, this._element[0], ['preshow', 'postshow', 'prehide', 'posthide', 'cancel'], function (detail) { if (detail.dialog) { detail.dialog = this; } return detail; }.bind(this)); this._scope.$on('$destroy', this._destroy.bind(this)); }, _destroy: function _destroy() { this.emit('destroy'); this._element.remove(); this._clearDerivingMethods(); this._clearDerivingEvents(); this._scope = this._attrs = this._element = null; } }); DialogView.registerAnimator = function (name, Animator) { return window.OnsDialogElement.registerAnimator(name, Animator); }; MicroEvent.mixin(DialogView); $onsen.derivePropertiesFromElement(DialogView, ['disabled', 'cancelable', 'visible', 'onDeviceBackButton']); return DialogView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION 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. */ angular.module('onsen').value('DialogAnimator', ons._internal.DialogAnimator).value('IOSDialogAnimator', ons._internal.IOSDialogAnimator).value('AndroidDialogAnimator', ons._internal.AndroidDialogAnimator).value('SlideDialogAnimator', ons._internal.SlideDialogAnimator); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; angular.module('onsen').factory('GenericView', ['$onsen', function ($onsen) { var GenericView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs * @param {Object} [options] * @param {Boolean} [options.directiveOnly] * @param {Function} [options.onDestroy] * @param {String} [options.modifierTemplate] */ init: function init(scope, element, attrs, options) { var self = this; options = {}; this._element = element; this._scope = scope; this._attrs = attrs; if (options.directiveOnly) { if (!options.modifierTemplate) { throw new Error('options.modifierTemplate is undefined.'); } $onsen.addModifierMethods(this, options.modifierTemplate, element); } else { $onsen.addModifierMethodsForCustomElements(this, element); } $onsen.cleaner.onDestroy(scope, function () { self._events = undefined; $onsen.removeModifierMethods(self); if (options.onDestroy) { options.onDestroy(self); } $onsen.clearComponent({ scope: scope, attrs: attrs, element: element }); self = element = self._element = self._scope = scope = self._attrs = attrs = options = null; }); } }); /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs * @param {Object} options * @param {String} options.viewKey * @param {Boolean} [options.directiveOnly] * @param {Function} [options.onDestroy] * @param {String} [options.modifierTemplate] */ GenericView.register = function (scope, element, attrs, options) { var view = new GenericView(scope, element, attrs, options); if (!options.viewKey) { throw new Error('options.viewKey is required.'); } $onsen.declareVarAttribute(attrs, view); element.data(options.viewKey, view); var destroy = options.onDestroy || angular.noop; options.onDestroy = function (view) { destroy(view); element.data(options.viewKey, null); }; return view; }; MicroEvent.mixin(GenericView); return GenericView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('LazyRepeatView', ['AngularLazyRepeatDelegate', function (AngularLazyRepeatDelegate) { var LazyRepeatView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function init(scope, element, attrs, linker) { var _this = this; this._element = element; this._scope = scope; this._attrs = attrs; this._linker = linker; ons._util.updateParentPosition(element[0]); var userDelegate = this._scope.$eval(this._attrs.onsLazyRepeat); var internalDelegate = new AngularLazyRepeatDelegate(userDelegate, element[0], element.scope()); this._provider = new ons._internal.LazyRepeatProvider(element[0].parentNode, internalDelegate); element.remove(); // Render when number of items change. this._scope.$watch(internalDelegate.countItems.bind(internalDelegate), this._provider._onChange.bind(this._provider)); this._scope.$on('$destroy', function () { _this._element = _this._scope = _this._attrs = _this._linker = null; }); } }); return LazyRepeatView; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; angular.module('onsen').factory('AngularLazyRepeatDelegate', ['$compile', function ($compile) { var directiveAttributes = ['ons-lazy-repeat', 'ons:lazy:repeat', 'ons_lazy_repeat', 'data-ons-lazy-repeat', 'x-ons-lazy-repeat']; var scheme = { configureItemScope: { type: 'function', safeCall: true }, destroyItemScope: { type: 'function', safeCall: true } }; var AngularLazyRepeatDelegate = function (_ons$_internal$LazyRe) { babelHelpers.inherits(AngularLazyRepeatDelegate, _ons$_internal$LazyRe); /** * @param {Object} userDelegate * @param {Element} templateElement * @param {Scope} parentScope */ function AngularLazyRepeatDelegate(userDelegate, templateElement, parentScope) { babelHelpers.classCallCheck(this, AngularLazyRepeatDelegate); var _this = babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(AngularLazyRepeatDelegate).call(this, userDelegate, templateElement)); _this._parentScope = parentScope; directiveAttributes.forEach(function (attr) { return templateElement.removeAttribute(attr); }); _this._linker = $compile(templateElement ? templateElement.cloneNode(true) : null); return _this; } babelHelpers.createClass(AngularLazyRepeatDelegate, [{ key: 'configureItemScope', value: function configureItemScope(item, scope) { return this._validated('configureItemScope', scheme)(item, scope); } }, { key: 'destroyItemScope', value: function destroyItemScope(item, element) { return this._validated('destroyItemScope', scheme)(item, element); } }, { key: '_usingBinding', value: function _usingBinding() { if (this._userDelegate.configureItemScope) { return true; } if (this._userDelegate.createItemContent) { return false; } throw new Error('`lazy-repeat` delegate object is vague.'); } }, { key: 'prepareItem', value: function prepareItem(index, done) { var _this2 = this; var scope = this._parentScope.$new(); this._addSpecialProperties(index, scope); if (this._usingBinding()) { this.configureItemScope(index, scope); } this._linker(scope, function (cloned) { var element = cloned[0]; if (!_this2._usingBinding()) { element = _this2._userDelegate.createItemContent(index, element); $compile(element)(scope); } done({ element: element, scope: scope }); }); } /** * @param {Number} index * @param {Object} scope */ }, { key: '_addSpecialProperties', value: function _addSpecialProperties(i, scope) { var last = this.countItems() - 1; angular.extend(scope, { $index: i, $first: i === 0, $last: i === last, $middle: i !== 0 && i !== last, $even: i % 2 === 0, $odd: i % 2 === 1 }); } }, { key: 'updateItem', value: function updateItem(index, item) { var _this3 = this; if (this._usingBinding()) { item.scope.$evalAsync(function () { return _this3.configureItemScope(index, item.scope); }); } else { babelHelpers.get(Object.getPrototypeOf(AngularLazyRepeatDelegate.prototype), 'updateItem', this).call(this, index, item); } } /** * @param {Number} index * @param {Object} item * @param {Object} item.scope * @param {Element} item.element */ }, { key: 'destroyItem', value: function destroyItem(index, item) { if (this._usingBinding()) { this.destroyItemScope(index, item.scope); } else { babelHelpers.get(Object.getPrototypeOf(AngularLazyRepeatDelegate.prototype), 'destroyItem', this).call(this, index, item.element); } item.scope.$destroy(); } }, { key: 'destroy', value: function destroy() { babelHelpers.get(Object.getPrototypeOf(AngularLazyRepeatDelegate.prototype), 'destroy', this).call(this); this._scope = null; } }]); return AngularLazyRepeatDelegate; }(ons._internal.LazyRepeatDelegate); return AngularLazyRepeatDelegate; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.value('ModalAnimator', ons._internal.ModalAnimator); module.value('FadeModalAnimator', ons._internal.FadeModalAnimator); module.factory('ModalView', ['$onsen', '$parse', function ($onsen, $parse) { var ModalView = Class.extend({ _element: undefined, _scope: undefined, init: function init(scope, element, attrs) { this._scope = scope; this._element = element; this._scope.$on('$destroy', this._destroy.bind(this)); element[0]._animatorFactory.setAnimationOptions($parse(attrs.animationOptions)()); }, show: function show(options) { return this._element[0].show(options); }, hide: function hide(options) { return this._element[0].hide(options); }, toggle: function toggle(options) { return this._element[0].toggle(options); }, _destroy: function _destroy() { this.emit('destroy', { page: this }); this._events = this._element = this._scope = null; } }); ModalView.registerAnimator = function (name, Animator) { return window.OnsModalElement.registerAnimator(name, Animator); }; MicroEvent.mixin(ModalView); $onsen.derivePropertiesFromElement(ModalView, ['onDeviceBackButton']); return ModalView; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('NavigatorView', ['$compile', '$onsen', function ($compile, $onsen) { /** * Manages the page navigation backed by page stack. * * @class NavigatorView */ var NavigatorView = Class.extend({ /** * @member {jqLite} Object */ _element: undefined, /** * @member {Object} Object */ _attrs: undefined, /** * @member {Object} */ _scope: undefined, /** * @param {Object} scope * @param {jqLite} element jqLite Object to manage with navigator * @param {Object} attrs */ init: function init(scope, element, attrs) { this._element = element || angular.element(window.document.body); this._scope = scope || this._element.scope(); this._attrs = attrs; this._previousPageScope = null; this._boundOnPrepop = this._onPrepop.bind(this); this._boundOnPostpop = this._onPostpop.bind(this); this._element.on('prepop', this._boundOnPrepop); this._element.on('postpop', this._boundOnPostpop); this._scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['prepush', 'postpush', 'prepop', 'postpop', 'init', 'show', 'hide', 'destroy'], function (detail) { if (detail.navigator) { detail.navigator = this; } return detail; }.bind(this)); this._clearDerivingMethods = $onsen.deriveMethods(this, element[0], ['insertPage', 'pushPage', 'bringPageTop', 'popPage', 'replacePage', 'resetToPage', 'canPopPage']); }, _onPrepop: function _onPrepop(event) { var pages = event.detail.navigator.pages; angular.element(pages[pages.length - 2]).data('_scope').$evalAsync(); this._previousPageScope = angular.element(pages[pages.length - 1]).data('_scope'); }, _onPostpop: function _onPostpop(event) { this._previousPageScope.$destroy(); }, _compileAndLink: function _compileAndLink(pageElement, callback) { var link = $compile(pageElement); var pageScope = this._createPageScope(); link(pageScope); pageScope.$evalAsync(function () { callback(pageElement); }); }, _destroy: function _destroy() { this.emit('destroy'); this._clearDerivingEvents(); this._clearDerivingMethods(); this._element.off('prepop', this._boundOnPrepop); this._element.off('postpop', this._boundOnPostpop); this._element = this._scope = this._attrs = null; }, _createPageScope: function _createPageScope() { return this._scope.$new(); } }); MicroEvent.mixin(NavigatorView); $onsen.derivePropertiesFromElement(NavigatorView, ['pages', 'topPage']); return NavigatorView; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION 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. */ angular.module('onsen').value('NavigatorTransitionAnimator', ons._internal.NavigatorTransitionAnimator).value('FadeTransitionAnimator', ons._internal.FadeNavigatorTransitionAnimator).value('IOSSlideTransitionAnimator', ons._internal.IOSSlideNavigatorTransitionAnimator).value('LiftTransitionAnimator', ons._internal.LiftNavigatorTransitionAnimator).value('NullTransitionAnimator', ons._internal.NavigatorTransitionAnimator).value('SimpleSlideTransitionAnimator', ons._internal.SimpleSlideNavigatorTransitionAnimator); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('OverlaySlidingMenuAnimator', ['SlidingMenuAnimator', function (SlidingMenuAnimator) { var OverlaySlidingMenuAnimator = SlidingMenuAnimator.extend({ _blackMask: undefined, _isRight: false, _element: false, _menuPage: false, _mainPage: false, _width: false, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function setup(element, mainPage, menuPage, options) { options = options || {}; this._width = options.width || '90%'; this._isRight = !!options.isRight; this._element = element; this._mainPage = mainPage; this._menuPage = menuPage; menuPage.css('box-shadow', '0px 0 10px 0px rgba(0, 0, 0, 0.2)'); menuPage.css({ width: options.width, display: 'none', zIndex: 2 }); // Fix for transparent menu page on iOS8. menuPage.css('-webkit-transform', 'translate3d(0px, 0px, 0px)'); mainPage.css({ zIndex: 1 }); if (this._isRight) { menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { menuPage.css({ right: 'auto', left: '-' + options.width }); } this._blackMask = angular.element('<div></div>').css({ backgroundColor: 'black', top: '0px', left: '0px', right: '0px', bottom: '0px', position: 'absolute', display: 'none', zIndex: 0 }); element.prepend(this._blackMask); }, /** * @param {Object} options * @param {String} options.width */ onResized: function onResized(options) { this._menuPage.css('width', options.width); if (this._isRight) { this._menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { this._menuPage.css({ right: 'auto', left: '-' + options.width }); } if (options.isOpened) { var max = this._menuPage[0].clientWidth; var menuStyle = this._generateMenuPageStyle(max); animit(this._menuPage[0]).queue(menuStyle).play(); } }, /** */ destroy: function destroy() { if (this._blackMask) { this._blackMask.remove(); this._blackMask = null; } this._mainPage.removeAttr('style'); this._menuPage.removeAttr('style'); this._element = this._mainPage = this._menuPage = null; }, /** * @param {Function} callback * @param {Boolean} instant */ openMenu: function openMenu(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; this._menuPage.css('display', 'block'); this._blackMask.css('display', 'block'); var max = this._menuPage[0].clientWidth; var menuStyle = this._generateMenuPageStyle(max); var mainPageStyle = this._generateMainPageStyle(max); setTimeout(function () { animit(this._mainPage[0]).wait(delay).queue(mainPageStyle, { duration: duration, timing: this.timing }).queue(function (done) { callback(); done(); }).play(); animit(this._menuPage[0]).wait(delay).queue(menuStyle, { duration: duration, timing: this.timing }).play(); }.bind(this), 1000 / 60); }, /** * @param {Function} callback * @param {Boolean} instant */ closeMenu: function closeMenu(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; this._blackMask.css({ display: 'block' }); var menuPageStyle = this._generateMenuPageStyle(0); var mainPageStyle = this._generateMainPageStyle(0); setTimeout(function () { animit(this._mainPage[0]).wait(delay).queue(mainPageStyle, { duration: duration, timing: this.timing }).queue(function (done) { this._menuPage.css('display', 'none'); callback(); done(); }.bind(this)).play(); animit(this._menuPage[0]).wait(delay).queue(menuPageStyle, { duration: duration, timing: this.timing }).play(); }.bind(this), 1000 / 60); }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function translateMenu(options) { this._menuPage.css('display', 'block'); this._blackMask.css({ display: 'block' }); var menuPageStyle = this._generateMenuPageStyle(Math.min(options.maxDistance, options.distance)); var mainPageStyle = this._generateMainPageStyle(Math.min(options.maxDistance, options.distance)); delete mainPageStyle.opacity; animit(this._menuPage[0]).queue(menuPageStyle).play(); if (Object.keys(mainPageStyle).length > 0) { animit(this._mainPage[0]).queue(mainPageStyle).play(); } }, _generateMenuPageStyle: function _generateMenuPageStyle(distance) { var x = this._isRight ? -distance : distance; var transform = 'translate3d(' + x + 'px, 0, 0)'; return { transform: transform, 'box-shadow': distance === 0 ? 'none' : '0px 0 10px 0px rgba(0, 0, 0, 0.2)' }; }, _generateMainPageStyle: function _generateMainPageStyle(distance) { var max = this._menuPage[0].clientWidth; var opacity = 1 - 0.1 * distance / max; return { opacity: opacity }; }, copy: function copy() { return new OverlaySlidingMenuAnimator(); } }); return OverlaySlidingMenuAnimator; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('PageView', ['$onsen', '$parse', function ($onsen, $parse) { var PageView = Class.extend({ init: function init(scope, element, attrs) { var _this = this; this._scope = scope; this._element = element; this._attrs = attrs; this._clearListener = scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['init', 'show', 'hide', 'destroy']); Object.defineProperty(this, 'onDeviceBackButton', { get: function get() { return _this._element[0].onDeviceBackButton; }, set: function set(value) { if (!_this._userBackButtonHandler) { _this._enableBackButtonHandler(); } _this._userBackButtonHandler = value; } }); if (this._attrs.ngDeviceBackButton || this._attrs.onDeviceBackButton) { this._enableBackButtonHandler(); } if (this._attrs.ngInfiniteScroll) { this._element[0].onInfiniteScroll = function (done) { $parse(_this._attrs.ngInfiniteScroll)(_this._scope)(done); }; } }, _enableBackButtonHandler: function _enableBackButtonHandler() { this._userBackButtonHandler = angular.noop; this._element[0].onDeviceBackButton = this._onDeviceBackButton.bind(this); }, _onDeviceBackButton: function _onDeviceBackButton($event) { this._userBackButtonHandler($event); // ng-device-backbutton if (this._attrs.ngDeviceBackButton) { $parse(this._attrs.ngDeviceBackButton)(this._scope, { $event: $event }); } // on-device-backbutton /* jshint ignore:start */ if (this._attrs.onDeviceBackButton) { var lastEvent = window.$event; window.$event = $event; new Function(this._attrs.onDeviceBackButton)(); // eslint-disable-line no-new-func window.$event = lastEvent; } /* jshint ignore:end */ }, _destroy: function _destroy() { this._clearDerivingEvents(); this._element = null; this._scope = null; this._clearListener(); } }); MicroEvent.mixin(PageView); return PageView; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; angular.module('onsen').factory('PopoverView', ['$onsen', function ($onsen) { var PopoverView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function init(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], ['show', 'hide']); this._clearDerivingEvents = $onsen.deriveEvents(this, this._element[0], ['preshow', 'postshow', 'prehide', 'posthide'], function (detail) { if (detail.popover) { detail.popover = this; } return detail; }.bind(this)); }, _destroy: function _destroy() { this.emit('destroy'); this._clearDerivingMethods(); this._clearDerivingEvents(); this._element.remove(); this._element = this._scope = null; } }); MicroEvent.mixin(PopoverView); $onsen.derivePropertiesFromElement(PopoverView, ['cancelable', 'disabled', 'onDeviceBackButton']); return PopoverView; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION 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. */ angular.module('onsen').value('PopoverAnimator', ons._internal.PopoverAnimator).value('FadePopoverAnimator', ons._internal.FadePopoverAnimator); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('PullHookView', ['$onsen', '$parse', function ($onsen, $parse) { var PullHookView = Class.extend({ init: function init(scope, element, attrs) { var _this = this; this._element = element; this._scope = scope; this._attrs = attrs; this._clearDerivingEvents = $onsen.deriveEvents(this, this._element[0], ['changestate'], function (detail) { if (detail.pullHook) { detail.pullHook = _this; } return detail; }); this.on('changestate', function () { return _this._scope.$evalAsync(); }); this._element[0].onAction = function (done) { if (_this._attrs.ngAction) { _this._scope.$eval(_this._attrs.ngAction, { $done: done }); } else { _this.onAction ? _this.onAction(done) : done(); } }; this._scope.$on('$destroy', this._destroy.bind(this)); }, _destroy: function _destroy() { this.emit('destroy'); this._clearDerivingEvents(); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(PullHookView); $onsen.derivePropertiesFromElement(PullHookView, ['state', 'pullDistance', 'height', 'thresholdHeight', 'disabled']); return PullHookView; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('PushSlidingMenuAnimator', ['SlidingMenuAnimator', function (SlidingMenuAnimator) { var PushSlidingMenuAnimator = SlidingMenuAnimator.extend({ _isRight: false, _element: undefined, _menuPage: undefined, _mainPage: undefined, _width: undefined, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function setup(element, mainPage, menuPage, options) { options = options || {}; this._element = element; this._mainPage = mainPage; this._menuPage = menuPage; this._isRight = !!options.isRight; this._width = options.width || '90%'; menuPage.css({ width: options.width, display: 'none' }); if (this._isRight) { menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { menuPage.css({ right: 'auto', left: '-' + options.width }); } }, /** * @param {Object} options * @param {String} options.width * @param {Object} options.isRight */ onResized: function onResized(options) { this._menuPage.css('width', options.width); if (this._isRight) { this._menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { this._menuPage.css({ right: 'auto', left: '-' + options.width }); } if (options.isOpened) { var max = this._menuPage[0].clientWidth; var mainPageTransform = this._generateAbovePageTransform(max); var menuPageStyle = this._generateBehindPageStyle(max); animit(this._mainPage[0]).queue({ transform: mainPageTransform }).play(); animit(this._menuPage[0]).queue(menuPageStyle).play(); } }, /** */ destroy: function destroy() { this._mainPage.removeAttr('style'); this._menuPage.removeAttr('style'); this._element = this._mainPage = this._menuPage = null; }, /** * @param {Function} callback * @param {Boolean} instant */ openMenu: function openMenu(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; this._menuPage.css('display', 'block'); var max = this._menuPage[0].clientWidth; var aboveTransform = this._generateAbovePageTransform(max); var behindStyle = this._generateBehindPageStyle(max); setTimeout(function () { animit(this._mainPage[0]).wait(delay).queue({ transform: aboveTransform }, { duration: duration, timing: this.timing }).queue(function (done) { callback(); done(); }).play(); animit(this._menuPage[0]).wait(delay).queue(behindStyle, { duration: duration, timing: this.timing }).play(); }.bind(this), 1000 / 60); }, /** * @param {Function} callback * @param {Boolean} instant */ closeMenu: function closeMenu(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; var aboveTransform = this._generateAbovePageTransform(0); var behindStyle = this._generateBehindPageStyle(0); setTimeout(function () { animit(this._mainPage[0]).wait(delay).queue({ transform: aboveTransform }, { duration: duration, timing: this.timing }).queue({ transform: 'translate3d(0, 0, 0)' }).queue(function (done) { this._menuPage.css('display', 'none'); callback(); done(); }.bind(this)).play(); animit(this._menuPage[0]).wait(delay).queue(behindStyle, { duration: duration, timing: this.timing }).queue(function (done) { done(); }).play(); }.bind(this), 1000 / 60); }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function translateMenu(options) { this._menuPage.css('display', 'block'); var aboveTransform = this._generateAbovePageTransform(Math.min(options.maxDistance, options.distance)); var behindStyle = this._generateBehindPageStyle(Math.min(options.maxDistance, options.distance)); animit(this._mainPage[0]).queue({ transform: aboveTransform }).play(); animit(this._menuPage[0]).queue(behindStyle).play(); }, _generateAbovePageTransform: function _generateAbovePageTransform(distance) { var x = this._isRight ? -distance : distance; var aboveTransform = 'translate3d(' + x + 'px, 0, 0)'; return aboveTransform; }, _generateBehindPageStyle: function _generateBehindPageStyle(distance) { var behindX = this._isRight ? -distance : distance; var behindTransform = 'translate3d(' + behindX + 'px, 0, 0)'; return { transform: behindTransform }; }, copy: function copy() { return new PushSlidingMenuAnimator(); } }); return PushSlidingMenuAnimator; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('RevealSlidingMenuAnimator', ['SlidingMenuAnimator', function (SlidingMenuAnimator) { var RevealSlidingMenuAnimator = SlidingMenuAnimator.extend({ _blackMask: undefined, _isRight: false, _menuPage: undefined, _element: undefined, _mainPage: undefined, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function setup(element, mainPage, menuPage, options) { this._element = element; this._menuPage = menuPage; this._mainPage = mainPage; this._isRight = !!options.isRight; this._width = options.width || '90%'; mainPage.css({ boxShadow: '0px 0 10px 0px rgba(0, 0, 0, 0.2)' }); menuPage.css({ width: options.width, opacity: 0.9, display: 'none' }); if (this._isRight) { menuPage.css({ right: '0px', left: 'auto' }); } else { menuPage.css({ right: 'auto', left: '0px' }); } this._blackMask = angular.element('<div></div>').css({ backgroundColor: 'black', top: '0px', left: '0px', right: '0px', bottom: '0px', position: 'absolute', display: 'none' }); element.prepend(this._blackMask); // Dirty fix for broken rendering bug on android 4.x. animit(mainPage[0]).queue({ transform: 'translate3d(0, 0, 0)' }).play(); }, /** * @param {Object} options * @param {Boolean} options.isOpened * @param {String} options.width */ onResized: function onResized(options) { this._width = options.width; this._menuPage.css('width', this._width); if (options.isOpened) { var max = this._menuPage[0].clientWidth; var aboveTransform = this._generateAbovePageTransform(max); var behindStyle = this._generateBehindPageStyle(max); animit(this._mainPage[0]).queue({ transform: aboveTransform }).play(); animit(this._menuPage[0]).queue(behindStyle).play(); } }, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage */ destroy: function destroy() { if (this._blackMask) { this._blackMask.remove(); this._blackMask = null; } if (this._mainPage) { this._mainPage.attr('style', ''); } if (this._menuPage) { this._menuPage.attr('style', ''); } this._mainPage = this._menuPage = this._element = undefined; }, /** * @param {Function} callback * @param {Boolean} instant */ openMenu: function openMenu(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; this._menuPage.css('display', 'block'); this._blackMask.css('display', 'block'); var max = this._menuPage[0].clientWidth; var aboveTransform = this._generateAbovePageTransform(max); var behindStyle = this._generateBehindPageStyle(max); setTimeout(function () { animit(this._mainPage[0]).wait(delay).queue({ transform: aboveTransform }, { duration: duration, timing: this.timing }).queue(function (done) { callback(); done(); }).play(); animit(this._menuPage[0]).wait(delay).queue(behindStyle, { duration: duration, timing: this.timing }).play(); }.bind(this), 1000 / 60); }, /** * @param {Function} callback * @param {Boolean} instant */ closeMenu: function closeMenu(callback, instant) { var duration = instant === true ? 0.0 : this.duration; var delay = instant === true ? 0.0 : this.delay; this._blackMask.css('display', 'block'); var aboveTransform = this._generateAbovePageTransform(0); var behindStyle = this._generateBehindPageStyle(0); setTimeout(function () { animit(this._mainPage[0]).wait(delay).queue({ transform: aboveTransform }, { duration: duration, timing: this.timing }).queue({ transform: 'translate3d(0, 0, 0)' }).queue(function (done) { this._menuPage.css('display', 'none'); callback(); done(); }.bind(this)).play(); animit(this._menuPage[0]).wait(delay).queue(behindStyle, { duration: duration, timing: this.timing }).queue(function (done) { done(); }).play(); }.bind(this), 1000 / 60); }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function translateMenu(options) { this._menuPage.css('display', 'block'); this._blackMask.css('display', 'block'); var aboveTransform = this._generateAbovePageTransform(Math.min(options.maxDistance, options.distance)); var behindStyle = this._generateBehindPageStyle(Math.min(options.maxDistance, options.distance)); delete behindStyle.opacity; animit(this._mainPage[0]).queue({ transform: aboveTransform }).play(); animit(this._menuPage[0]).queue(behindStyle).play(); }, _generateAbovePageTransform: function _generateAbovePageTransform(distance) { var x = this._isRight ? -distance : distance; var aboveTransform = 'translate3d(' + x + 'px, 0, 0)'; return aboveTransform; }, _generateBehindPageStyle: function _generateBehindPageStyle(distance) { var max = this._menuPage[0].getBoundingClientRect().width; var behindDistance = (distance - max) / max * 10; behindDistance = isNaN(behindDistance) ? 0 : Math.max(Math.min(behindDistance, 0), -10); var behindX = this._isRight ? -behindDistance : behindDistance; var behindTransform = 'translate3d(' + behindX + '%, 0, 0)'; var opacity = 1 + behindDistance / 100; return { transform: behindTransform, opacity: opacity }; }, copy: function copy() { return new RevealSlidingMenuAnimator(); } }); return RevealSlidingMenuAnimator; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); var SlidingMenuViewModel = Class.extend({ /** * @member Number */ _distance: 0, /** * @member Number */ _maxDistance: undefined, /** * @param {Object} options * @param {Number} maxDistance */ init: function init(options) { if (!angular.isNumber(options.maxDistance)) { throw new Error('options.maxDistance must be number'); } this.setMaxDistance(options.maxDistance); }, /** * @param {Number} maxDistance */ setMaxDistance: function setMaxDistance(maxDistance) { if (maxDistance <= 0) { throw new Error('maxDistance must be greater then zero.'); } if (this.isOpened()) { this._distance = maxDistance; } this._maxDistance = maxDistance; }, /** * @return {Boolean} */ shouldOpen: function shouldOpen() { return !this.isOpened() && this._distance >= this._maxDistance / 2; }, /** * @return {Boolean} */ shouldClose: function shouldClose() { return !this.isClosed() && this._distance < this._maxDistance / 2; }, openOrClose: function openOrClose(options) { if (this.shouldOpen()) { this.open(options); } else if (this.shouldClose()) { this.close(options); } }, close: function close(options) { var callback = options.callback || function () {}; if (!this.isClosed()) { this._distance = 0; this.emit('close', options); } else { callback(); } }, open: function open(options) { var callback = options.callback || function () {}; if (!this.isOpened()) { this._distance = this._maxDistance; this.emit('open', options); } else { callback(); } }, /** * @return {Boolean} */ isClosed: function isClosed() { return this._distance === 0; }, /** * @return {Boolean} */ isOpened: function isOpened() { return this._distance === this._maxDistance; }, /** * @return {Number} */ getX: function getX() { return this._distance; }, /** * @return {Number} */ getMaxDistance: function getMaxDistance() { return this._maxDistance; }, /** * @param {Number} x */ translate: function translate(x) { this._distance = Math.max(1, Math.min(this._maxDistance - 1, x)); var options = { distance: this._distance, maxDistance: this._maxDistance }; this.emit('translate', options); }, toggle: function toggle() { if (this.isClosed()) { this.open(); } else { this.close(); } } }); MicroEvent.mixin(SlidingMenuViewModel); module.factory('SlidingMenuView', ['$onsen', '$compile', '$parse', 'AnimationChooser', 'SlidingMenuAnimator', 'RevealSlidingMenuAnimator', 'PushSlidingMenuAnimator', 'OverlaySlidingMenuAnimator', function ($onsen, $compile, $parse, AnimationChooser, SlidingMenuAnimator, RevealSlidingMenuAnimator, PushSlidingMenuAnimator, OverlaySlidingMenuAnimator) { var SlidingMenuView = Class.extend({ _scope: undefined, _attrs: undefined, _element: undefined, _menuPage: undefined, _mainPage: undefined, _doorLock: undefined, _isRightMenu: false, init: function init(scope, element, attrs) { this._scope = scope; this._attrs = attrs; this._element = element; this._menuPage = angular.element(element[0].querySelector('.onsen-sliding-menu__menu')); this._mainPage = angular.element(element[0].querySelector('.onsen-sliding-menu__main')); this._doorLock = new ons._DoorLock(); this._isRightMenu = attrs.side === 'right'; // Close menu on tap event. this._mainPageGestureDetector = new ons.GestureDetector(this._mainPage[0]); this._boundOnTap = this._onTap.bind(this); var maxDistance = this._normalizeMaxSlideDistanceAttr(); this._logic = new SlidingMenuViewModel({ maxDistance: Math.max(maxDistance, 1) }); this._logic.on('translate', this._translate.bind(this)); this._logic.on('open', function (options) { this._open(options); }.bind(this)); this._logic.on('close', function (options) { this._close(options); }.bind(this)); attrs.$observe('maxSlideDistance', this._onMaxSlideDistanceChanged.bind(this)); attrs.$observe('swipeable', this._onSwipeableChanged.bind(this)); this._boundOnWindowResize = this._onWindowResize.bind(this); window.addEventListener('resize', this._boundOnWindowResize); this._boundHandleEvent = this._handleEvent.bind(this); this._bindEvents(); if (attrs.mainPage) { this.setMainPage(attrs.mainPage); } if (attrs.menuPage) { this.setMenuPage(attrs.menuPage); } this._deviceBackButtonHandler = ons._deviceBackButtonDispatcher.createHandler(this._element[0], this._onDeviceBackButton.bind(this)); var unlock = this._doorLock.lock(); window.setTimeout(function () { var maxDistance = this._normalizeMaxSlideDistanceAttr(); this._logic.setMaxDistance(maxDistance); this._menuPage.css({ opacity: 1 }); var animationChooser = new AnimationChooser({ animators: SlidingMenuView._animatorDict, baseClass: SlidingMenuAnimator, baseClassName: 'SlidingMenuAnimator', defaultAnimation: attrs.type, defaultAnimationOptions: $parse(attrs.animationOptions)() }); this._animator = animationChooser.newAnimator(); this._animator.setup(this._element, this._mainPage, this._menuPage, { isRight: this._isRightMenu, width: this._attrs.maxSlideDistance || '90%' }); unlock(); }.bind(this), 400); scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['init', 'show', 'hide', 'destroy']); if (!attrs.swipeable) { this.setSwipeable(true); } }, getDeviceBackButtonHandler: function getDeviceBackButtonHandler() { return this._deviceBackButtonHandler; }, _onDeviceBackButton: function _onDeviceBackButton(event) { if (this.isMenuOpened()) { this.closeMenu(); } else { event.callParentHandler(); } }, _onTap: function _onTap() { if (this.isMenuOpened()) { this.closeMenu(); } }, _refreshMenuPageWidth: function _refreshMenuPageWidth() { var width = 'maxSlideDistance' in this._attrs ? this._attrs.maxSlideDistance : '90%'; if (this._animator) { this._animator.onResized({ isOpened: this._logic.isOpened(), width: width }); } }, _destroy: function _destroy() { this.emit('destroy'); this._clearDerivingEvents(); this._deviceBackButtonHandler.destroy(); window.removeEventListener('resize', this._boundOnWindowResize); this._mainPageGestureDetector.off('tap', this._boundOnTap); this._element = this._scope = this._attrs = null; }, _onSwipeableChanged: function _onSwipeableChanged(swipeable) { swipeable = swipeable === '' || swipeable === undefined || swipeable == 'true'; this.setSwipeable(swipeable); }, /** * @param {Boolean} enabled */ setSwipeable: function setSwipeable(enabled) { if (enabled) { this._activateGestureDetector(); } else { this._deactivateGestureDetector(); } }, _onWindowResize: function _onWindowResize() { this._recalculateMAX(); this._refreshMenuPageWidth(); }, _onMaxSlideDistanceChanged: function _onMaxSlideDistanceChanged() { this._recalculateMAX(); this._refreshMenuPageWidth(); }, /** * @return {Number} */ _normalizeMaxSlideDistanceAttr: function _normalizeMaxSlideDistanceAttr() { var maxDistance = this._attrs.maxSlideDistance; if (!('maxSlideDistance' in this._attrs)) { maxDistance = 0.9 * this._mainPage[0].clientWidth; } else if (typeof maxDistance == 'string') { if (maxDistance.indexOf('px', maxDistance.length - 2) !== -1) { maxDistance = parseInt(maxDistance.replace('px', ''), 10); } else if (maxDistance.indexOf('%', maxDistance.length - 1) > 0) { maxDistance = maxDistance.replace('%', ''); maxDistance = parseFloat(maxDistance) / 100 * this._mainPage[0].clientWidth; } } else { throw new Error('invalid state'); } return maxDistance; }, _recalculateMAX: function _recalculateMAX() { var maxDistance = this._normalizeMaxSlideDistanceAttr(); if (maxDistance) { this._logic.setMaxDistance(parseInt(maxDistance, 10)); } }, _activateGestureDetector: function _activateGestureDetector() { this._gestureDetector.on('touch dragleft dragright swipeleft swiperight release', this._boundHandleEvent); }, _deactivateGestureDetector: function _deactivateGestureDetector() { this._gestureDetector.off('touch dragleft dragright swipeleft swiperight release', this._boundHandleEvent); }, _bindEvents: function _bindEvents() { this._gestureDetector = new ons.GestureDetector(this._element[0], { dragMinDistance: 1 }); }, _appendMainPage: function _appendMainPage(pageUrl, templateHTML) { var pageScope = this._scope.$new(); var pageContent = angular.element(templateHTML); var link = $compile(pageContent); this._mainPage.append(pageContent); if (this._currentPageElement) { this._currentPageElement.remove(); this._currentPageScope.$destroy(); } link(pageScope); this._currentPageElement = pageContent; this._currentPageScope = pageScope; this._currentPageUrl = pageUrl; this._currentPageElement[0]._show(); }, /** * @param {String} */ _appendMenuPage: function _appendMenuPage(templateHTML) { var pageScope = this._scope.$new(); var pageContent = angular.element(templateHTML); var link = $compile(pageContent); this._menuPage.append(pageContent); if (this._currentMenuPageScope) { this._currentMenuPageScope.$destroy(); this._currentMenuPageElement.remove(); } link(pageScope); this._currentMenuPageElement = pageContent; this._currentMenuPageScope = pageScope; }, /** * @param {String} page * @param {Object} options * @param {Boolean} [options.closeMenu] * @param {Boolean} [options.callback] */ setMenuPage: function setMenuPage(page, options) { if (page) { options = options || {}; options.callback = options.callback || function () {}; var self = this; $onsen.getPageHTMLAsync(page).then(function (html) { self._appendMenuPage(angular.element(html)); if (options.closeMenu) { self.close(); } options.callback(); }, function () { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, /** * @param {String} pageUrl * @param {Object} options * @param {Boolean} [options.closeMenu] * @param {Boolean} [options.callback] */ setMainPage: function setMainPage(pageUrl, options) { options = options || {}; options.callback = options.callback || function () {}; var done = function () { if (options.closeMenu) { this.close(); } options.callback(); }.bind(this); if (this._currentPageUrl === pageUrl) { done(); return; } if (pageUrl) { var self = this; $onsen.getPageHTMLAsync(pageUrl).then(function (html) { self._appendMainPage(pageUrl, html); done(); }, function () { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, _handleEvent: function _handleEvent(event) { if (this._doorLock.isLocked()) { return; } if (this._isInsideIgnoredElement(event.target)) { this._deactivateGestureDetector(); } switch (event.type) { case 'dragleft': case 'dragright': if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) { return; } event.gesture.preventDefault(); var deltaX = event.gesture.deltaX; var deltaDistance = this._isRightMenu ? -deltaX : deltaX; var startEvent = event.gesture.startEvent; if (!('isOpened' in startEvent)) { startEvent.isOpened = this._logic.isOpened(); } if (deltaDistance < 0 && this._logic.isClosed()) { break; } if (deltaDistance > 0 && this._logic.isOpened()) { break; } var distance = startEvent.isOpened ? deltaDistance + this._logic.getMaxDistance() : deltaDistance; this._logic.translate(distance); break; case 'swipeleft': event.gesture.preventDefault(); if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) { return; } if (this._isRightMenu) { this.open(); } else { this.close(); } event.gesture.stopDetect(); break; case 'swiperight': event.gesture.preventDefault(); if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) { return; } if (this._isRightMenu) { this.close(); } else { this.open(); } event.gesture.stopDetect(); break; case 'release': this._lastDistance = null; if (this._logic.shouldOpen()) { this.open(); } else if (this._logic.shouldClose()) { this.close(); } break; } }, /** * @param {jqLite} element * @return {Boolean} */ _isInsideIgnoredElement: function _isInsideIgnoredElement(element) { do { if (element.getAttribute && element.getAttribute('sliding-menu-ignore')) { return true; } element = element.parentNode; } while (element); return false; }, _isInsideSwipeTargetArea: function _isInsideSwipeTargetArea(event) { var x = event.gesture.center.pageX; if (!('_swipeTargetWidth' in event.gesture.startEvent)) { event.gesture.startEvent._swipeTargetWidth = this._getSwipeTargetWidth(); } var targetWidth = event.gesture.startEvent._swipeTargetWidth; return this._isRightMenu ? this._mainPage[0].clientWidth - x < targetWidth : x < targetWidth; }, _getSwipeTargetWidth: function _getSwipeTargetWidth() { var targetWidth = this._attrs.swipeTargetWidth; if (typeof targetWidth == 'string') { targetWidth = targetWidth.replace('px', ''); } var width = parseInt(targetWidth, 10); if (width < 0 || !targetWidth) { return this._mainPage[0].clientWidth; } else { return width; } }, closeMenu: function closeMenu() { return this.close.apply(this, arguments); }, /** * Close sliding-menu page. * * @param {Object} options */ close: function close(options) { options = options || {}; options = typeof options == 'function' ? { callback: options } : options; if (!this._logic.isClosed()) { this.emit('preclose', { slidingMenu: this }); this._doorLock.waitUnlock(function () { this._logic.close(options); }.bind(this)); } }, _close: function _close(options) { var callback = options.callback || function () {}, unlock = this._doorLock.lock(), instant = options.animation == 'none'; this._animator.closeMenu(function () { unlock(); this._mainPage.children().css('pointer-events', ''); this._mainPageGestureDetector.off('tap', this._boundOnTap); this.emit('postclose', { slidingMenu: this }); callback(); }.bind(this), instant); }, /** * Open sliding-menu page. * * @param {Object} [options] * @param {Function} [options.callback] */ openMenu: function openMenu() { return this.open.apply(this, arguments); }, /** * Open sliding-menu page. * * @param {Object} [options] * @param {Function} [options.callback] */ open: function open(options) { options = options || {}; options = typeof options == 'function' ? { callback: options } : options; this.emit('preopen', { slidingMenu: this }); this._doorLock.waitUnlock(function () { this._logic.open(options); }.bind(this)); }, _open: function _open(options) { var callback = options.callback || function () {}, unlock = this._doorLock.lock(), instant = options.animation == 'none'; this._animator.openMenu(function () { unlock(); this._mainPage.children().css('pointer-events', 'none'); this._mainPageGestureDetector.on('tap', this._boundOnTap); this.emit('postopen', { slidingMenu: this }); callback(); }.bind(this), instant); }, /** * Toggle sliding-menu page. * @param {Object} [options] * @param {Function} [options.callback] */ toggle: function toggle(options) { if (this._logic.isClosed()) { this.open(options); } else { this.close(options); } }, /** * Toggle sliding-menu page. */ toggleMenu: function toggleMenu() { return this.toggle.apply(this, arguments); }, /** * @return {Boolean} */ isMenuOpened: function isMenuOpened() { return this._logic.isOpened(); }, /** * @param {Object} event */ _translate: function _translate(event) { this._animator.translateMenu(event); } }); // Preset sliding menu animators. SlidingMenuView._animatorDict = { 'default': RevealSlidingMenuAnimator, 'overlay': OverlaySlidingMenuAnimator, 'reveal': RevealSlidingMenuAnimator, 'push': PushSlidingMenuAnimator }; /** * @param {String} name * @param {Function} Animator */ SlidingMenuView.registerAnimator = function (name, Animator) { if (!(Animator.prototype instanceof SlidingMenuAnimator)) { throw new Error('"Animator" param must inherit SlidingMenuAnimator'); } this._animatorDict[name] = Animator; }; MicroEvent.mixin(SlidingMenuView); return SlidingMenuView; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('SlidingMenuAnimator', function () { return Class.extend({ delay: 0, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)', /** * @param {Object} options * @param {String} options.timing * @param {Number} options.duration * @param {Number} options.delay */ init: function init(options) { options = options || {}; this.timing = options.timing || this.timing; this.duration = options.duration !== undefined ? options.duration : this.duration; this.delay = options.delay !== undefined ? options.delay : this.delay; }, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function setup(element, mainPage, menuPage, options) {}, /** * @param {Object} options * @param {Boolean} options.isRight * @param {Boolean} options.isOpened * @param {String} options.width */ onResized: function onResized(options) {}, /** * @param {Function} callback */ openMenu: function openMenu(callback) {}, /** * @param {Function} callback */ closeClose: function closeClose(callback) {}, /** */ destroy: function destroy() {}, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function translateMenu(mainPage, menuPage, options) {}, /** * @return {SlidingMenuAnimator} */ copy: function copy() { throw new Error('Override copy method.'); } }); }); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.factory('SplitView', ['$compile', 'RevealSlidingMenuAnimator', '$onsen', '$onsGlobal', function ($compile, RevealSlidingMenuAnimator, $onsen, $onsGlobal) { var SPLIT_MODE = 0; var COLLAPSE_MODE = 1; var MAIN_PAGE_RATIO = 0.9; var SplitView = Class.extend({ init: function init(scope, element, attrs) { element.addClass('onsen-sliding-menu'); this._element = element; this._scope = scope; this._attrs = attrs; this._mainPage = angular.element(element[0].querySelector('.onsen-split-view__main')); this._secondaryPage = angular.element(element[0].querySelector('.onsen-split-view__secondary')); this._max = this._mainPage[0].clientWidth * MAIN_PAGE_RATIO; this._mode = SPLIT_MODE; this._doorLock = new ons._DoorLock(); this._doSplit = false; this._doCollapse = false; $onsGlobal.orientation.on('change', this._onResize.bind(this)); this._animator = new RevealSlidingMenuAnimator(); this._element.css('display', 'none'); if (attrs.mainPage) { this.setMainPage(attrs.mainPage); } if (attrs.secondaryPage) { this.setSecondaryPage(attrs.secondaryPage); } var unlock = this._doorLock.lock(); this._considerChangingCollapse(); this._setSize(); setTimeout(function () { this._element.css('display', 'block'); unlock(); }.bind(this), 1000 / 60 * 2); scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['init', 'show', 'hide', 'destroy']); }, /** * @param {String} templateHTML */ _appendSecondPage: function _appendSecondPage(templateHTML) { var pageScope = this._scope.$new(); var pageContent = $compile(templateHTML)(pageScope); this._secondaryPage.append(pageContent); if (this._currentSecondaryPageElement) { this._currentSecondaryPageElement.remove(); this._currentSecondaryPageScope.$destroy(); } this._currentSecondaryPageElement = pageContent; this._currentSecondaryPageScope = pageScope; }, /** * @param {String} templateHTML */ _appendMainPage: function _appendMainPage(templateHTML) { var pageScope = this._scope.$new(); var pageContent = $compile(templateHTML)(pageScope); this._mainPage.append(pageContent); if (this._currentPage) { this._currentPageScope.$destroy(); } this._currentPage = pageContent; this._currentPageScope = pageScope; this._currentPage[0]._show(); }, /** * @param {String} page */ setSecondaryPage: function setSecondaryPage(page) { if (page) { $onsen.getPageHTMLAsync(page).then(function (html) { this._appendSecondPage(angular.element(html.trim())); }.bind(this), function () { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, /** * @param {String} page */ setMainPage: function setMainPage(page) { if (page) { $onsen.getPageHTMLAsync(page).then(function (html) { this._appendMainPage(angular.element(html.trim())); }.bind(this), function () { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, _onResize: function _onResize() { var lastMode = this._mode; this._considerChangingCollapse(); if (lastMode === COLLAPSE_MODE && this._mode === COLLAPSE_MODE) { this._animator.onResized({ isOpened: false, width: '90%' }); } this._max = this._mainPage[0].clientWidth * MAIN_PAGE_RATIO; }, _considerChangingCollapse: function _considerChangingCollapse() { var should = this._shouldCollapse(); if (should && this._mode !== COLLAPSE_MODE) { this._fireUpdateEvent(); if (this._doSplit) { this._activateSplitMode(); } else { this._activateCollapseMode(); } } else if (!should && this._mode === COLLAPSE_MODE) { this._fireUpdateEvent(); if (this._doCollapse) { this._activateCollapseMode(); } else { this._activateSplitMode(); } } this._doCollapse = this._doSplit = false; }, update: function update() { this._fireUpdateEvent(); var should = this._shouldCollapse(); if (this._doSplit) { this._activateSplitMode(); } else if (this._doCollapse) { this._activateCollapseMode(); } else if (should) { this._activateCollapseMode(); } else if (!should) { this._activateSplitMode(); } this._doSplit = this._doCollapse = false; }, _getOrientation: function _getOrientation() { if ($onsGlobal.orientation.isPortrait()) { return 'portrait'; } else { return 'landscape'; } }, getCurrentMode: function getCurrentMode() { if (this._mode === COLLAPSE_MODE) { return 'collapse'; } else { return 'split'; } }, _shouldCollapse: function _shouldCollapse() { var c = 'portrait'; if (typeof this._attrs.collapse === 'string') { c = this._attrs.collapse.trim(); } if (c == 'portrait') { return $onsGlobal.orientation.isPortrait(); } else if (c == 'landscape') { return $onsGlobal.orientation.isLandscape(); } else if (c.substr(0, 5) == 'width') { var num = c.split(' ')[1]; if (num.indexOf('px') >= 0) { num = num.substr(0, num.length - 2); } var width = window.innerWidth; return isNumber(num) && width < num; } else { var mq = window.matchMedia(c); return mq.matches; } }, _setSize: function _setSize() { if (this._mode === SPLIT_MODE) { if (!this._attrs.mainPageWidth) { this._attrs.mainPageWidth = '70'; } var secondarySize = 100 - this._attrs.mainPageWidth.replace('%', ''); this._secondaryPage.css({ width: secondarySize + '%', opacity: 1 }); this._mainPage.css({ width: this._attrs.mainPageWidth + '%' }); this._mainPage.css('left', secondarySize + '%'); } }, _fireEvent: function _fireEvent(name) { this.emit(name, { splitView: this, width: window.innerWidth, orientation: this._getOrientation() }); }, _fireUpdateEvent: function _fireUpdateEvent() { var that = this; this.emit('update', { splitView: this, shouldCollapse: this._shouldCollapse(), currentMode: this.getCurrentMode(), split: function split() { that._doSplit = true; that._doCollapse = false; }, collapse: function collapse() { that._doSplit = false; that._doCollapse = true; }, width: window.innerWidth, orientation: this._getOrientation() }); }, _activateCollapseMode: function _activateCollapseMode() { if (this._mode !== COLLAPSE_MODE) { this._fireEvent('precollapse'); this._secondaryPage.attr('style', ''); this._mainPage.attr('style', ''); this._mode = COLLAPSE_MODE; this._animator.setup(this._element, this._mainPage, this._secondaryPage, { isRight: false, width: '90%' }); this._fireEvent('postcollapse'); } }, _activateSplitMode: function _activateSplitMode() { if (this._mode !== SPLIT_MODE) { this._fireEvent('presplit'); this._animator.destroy(); this._secondaryPage.attr('style', ''); this._mainPage.attr('style', ''); this._mode = SPLIT_MODE; this._setSize(); this._fireEvent('postsplit'); } }, _destroy: function _destroy() { this.emit('destroy'); this._clearDerivingEvents(); this._element = null; this._scope = null; } }); function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } MicroEvent.mixin(SplitView); return SplitView; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; angular.module('onsen').factory('SplitterContent', ['$onsen', '$compile', function ($onsen, $compile) { var SplitterContent = Class.extend({ init: function init(scope, element, attrs) { var _this = this; this._element = element; this._scope = scope; this._attrs = attrs; this.load = function () { var _element$; _this._pageScope && _this._pageScope.$destroy(); return (_element$ = _this._element[0]).load.apply(_element$, arguments); }; scope.$on('$destroy', this._destroy.bind(this)); }, _link: function _link(fragment, done) { this._pageScope = this._scope.$new(); $compile(fragment)(this._pageScope); this._pageScope.$evalAsync(function () { return done(fragment); }); }, _destroy: function _destroy() { this.emit('destroy'); this._element = this._scope = this._attrs = this.load = this._pageScope = null; } }); MicroEvent.mixin(SplitterContent); $onsen.derivePropertiesFromElement(SplitterContent, ['page']); return SplitterContent; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; angular.module('onsen').factory('SplitterSide', ['$onsen', '$compile', function ($onsen, $compile) { var SplitterSide = Class.extend({ init: function init(scope, element, attrs) { var _this = this; this._element = element; this._scope = scope; this._attrs = attrs; this._clearDerivingMethods = $onsen.deriveMethods(this, this._element[0], ['open', 'close', 'toggle']); this.load = function () { var _element$; _this._pageScope && _this._pageScope.$destroy(); return (_element$ = _this._element[0]).load.apply(_element$, arguments); }; this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['modechange', 'preopen', 'preclose', 'postopen', 'postclose'], function (detail) { return detail.side ? angular.extend(detail, { side: _this }) : detail; }); scope.$on('$destroy', this._destroy.bind(this)); }, _link: function _link(fragment, done) { var link = $compile(fragment); this._pageScope = this._scope.$new(); link(this._pageScope); this._pageScope.$evalAsync(function () { return done(fragment); }); }, _destroy: function _destroy() { this.emit('destroy'); this._clearDerivingMethods(); this._clearDerivingEvents(); this._element = this._scope = this._attrs = this.load = this._pageScope = null; } }); MicroEvent.mixin(SplitterSide); $onsen.derivePropertiesFromElement(SplitterSide, ['page', 'mode', 'isOpen']); return SplitterSide; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; angular.module('onsen').factory('Splitter', ['$onsen', function ($onsen) { var Splitter = Class.extend({ init: function init(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; scope.$on('$destroy', this._destroy.bind(this)); }, _destroy: function _destroy() { this.emit('destroy'); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(Splitter); $onsen.derivePropertiesFromElement(Splitter, ['onDeviceBackButton']); ['left', 'right', 'content', 'mask'].forEach(function (prop, i) { Object.defineProperty(Splitter.prototype, prop, { get: function get() { var tagName = 'ons-splitter-' + (i < 2 ? 'side' : prop); return angular.element(this._element[0][prop]).data(tagName); } }); }); return Splitter; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; angular.module('onsen').factory('SwitchView', ['$parse', '$onsen', function ($parse, $onsen) { var SwitchView = Class.extend({ /** * @param {jqLite} element * @param {Object} scope * @param {Object} attrs */ init: function init(element, scope, attrs) { var _this = this; this._element = element; this._checkbox = angular.element(element[0].querySelector('input[type=checkbox]')); this._scope = scope; this._checkbox.on('change', function () { _this.emit('change', { 'switch': _this, value: _this._checkbox[0].checked, isInteractive: true }); }); this._prepareNgModel(element, scope, attrs); this._scope.$on('$destroy', function () { _this.emit('destroy'); _this._element = _this._checkbox = _this._scope = null; }); }, _prepareNgModel: function _prepareNgModel(element, scope, attrs) { var _this2 = this; if (attrs.ngModel) { var set = $parse(attrs.ngModel).assign; scope.$parent.$watch(attrs.ngModel, function (value) { _this2.checked = !!value; }); this._checkbox.on('change', function (e) { set(scope.$parent, _this2.checked); if (attrs.ngChange) { scope.$eval(attrs.ngChange); } scope.$parent.$evalAsync(); }); } } }); MicroEvent.mixin(SwitchView); $onsen.derivePropertiesFromElement(SwitchView, ['disabled', 'checked', 'checkbox']); return SwitchView; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); module.value('TabbarNoneAnimator', ons._internal.TabbarNoneAnimator); module.value('TabbarFadeAnimator', ons._internal.TabbarFadeAnimator); module.value('TabbarSlideAnimator', ons._internal.TabbarSlideAnimator); module.factory('TabbarView', ['$onsen', '$compile', '$parse', function ($onsen, $compile, $parse) { var TabbarView = Class.extend({ init: function init(scope, element, attrs) { if (element[0].nodeName.toLowerCase() !== 'ons-tabbar') { throw new Error('"element" parameter must be a "ons-tabbar" element.'); } this._scope = scope; this._element = element; this._attrs = attrs; this._lastPageElement = null; this._lastPageScope = null; this._scope.$on('$destroy', this._destroy.bind(this)); this._clearDerivingEvents = $onsen.deriveEvents(this, element[0], ['reactive', 'postchange', 'prechange', 'init', 'show', 'hide', 'destroy']); this._clearDerivingMethods = $onsen.deriveMethods(this, element[0], ['setActiveTab', 'setTabbarVisibility', 'getActiveTabIndex', 'loadPage']); }, _compileAndLink: function _compileAndLink(pageElement, callback) { var link = $compile(pageElement); var pageScope = this._scope.$new(); link(pageScope); pageScope.$evalAsync(function () { callback(pageElement); }); }, _destroy: function _destroy() { this.emit('destroy'); this._clearDerivingEvents(); this._clearDerivingMethods(); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(TabbarView); TabbarView.registerAnimator = function (name, Animator) { return window.OnsTabbarElement.registerAnimator(name, Animator); }; return TabbarView; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-alert-dialog */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this alert dialog.[/en] * [ja]このアラートダイアログを参照するための名前を指定します。[/ja] */ /** * @attribute ons-preshow * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en] * [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-prehide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en] * [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postshow * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en] * [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-posthide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en] * [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火された際に呼び出されるコールバックを指定します。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出されるコールバックを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしlistenerパラメータが指定されなかった場合、そのイベントのリスナーが全て削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーの関数オブジェクトを渡します。[/ja] */ (function () { 'use strict'; /** * Alert dialog directive. */ angular.module('onsen').directive('onsAlertDialog', ['$onsen', 'AlertDialogView', function ($onsen, AlertDialogView) { return { restrict: 'E', replace: false, scope: true, transclude: false, compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function pre(scope, element, attrs) { CustomElements.upgrade(element[0]); var alertDialog = new AlertDialogView(scope, element, attrs); $onsen.declareVarAttribute(attrs, alertDialog); $onsen.registerEventHandlers(alertDialog, 'preshow prehide postshow posthide destroy'); $onsen.addModifierMethodsForCustomElements(alertDialog, element); element.data('ons-alert-dialog', alertDialog); scope.$on('$destroy', function () { alertDialog._events = undefined; $onsen.removeModifierMethods(alertDialog); element.data('ons-alert-dialog', undefined); element = null; }); }, post: function post(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsBackButton', ['$onsen', '$compile', 'GenericView', 'ComponentCleaner', function ($onsen, $compile, GenericView, ComponentCleaner) { return { restrict: 'E', replace: false, compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function pre(scope, element, attrs, controller, transclude) { CustomElements.upgrade(element[0]); var backButton = GenericView.register(scope, element, attrs, { viewKey: 'ons-back-button' }); scope.$on('$destroy', function () { backButton._events = undefined; $onsen.removeModifierMethods(backButton); element = null; }); ComponentCleaner.onDestroy(scope, function () { ComponentCleaner.destroyScope(scope); ComponentCleaner.destroyAttributes(attrs); element = scope = attrs = null; }); }, post: function post(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; angular.module('onsen').directive('onsBottomToolbar', ['$onsen', 'GenericView', function ($onsen, GenericView) { return { restrict: 'E', link: { pre: function pre(scope, element, attrs) { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, { viewKey: 'ons-bottomToolbar' }); }, post: function post(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-button */ (function () { 'use strict'; angular.module('onsen').directive('onsButton', ['$onsen', 'GenericView', function ($onsen, GenericView) { return { restrict: 'E', link: function link(scope, element, attrs) { CustomElements.upgrade(element[0]); var button = GenericView.register(scope, element, attrs, { viewKey: 'ons-button' }); Object.defineProperty(button, 'disabled', { get: function get() { return this._element[0].disabled; }, set: function set(value) { return this._element[0].disabled = value; } }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-carousel * @description * [en]Carousel component.[/en] * [ja]カルーセルを表示できるコンポーネント。[/ja] * @codepen xbbzOQ * @guide UsingCarousel * [en]Learn how to use the carousel component.[/en] * [ja]carouselコンポーネントの使い方[/ja] * @example * <ons-carousel style="width: 100%; height: 200px"> * <ons-carousel-item> * ... * </ons-carousel-item> * <ons-carousel-item> * ... * </ons-carousel-item> * </ons-carousel> */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this carousel.[/en] * [ja]このカルーセルを参照するための変数名を指定します。[/ja] */ /** * @attribute ons-postchange * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postchange" event is fired.[/en] * [ja]"postchange"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-refresh * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "refresh" event is fired.[/en] * [ja]"refresh"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-overscroll * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "overscroll" event is fired.[/en] * [ja]"overscroll"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーが指定されなかった場合には、そのイベントに紐付いているイベントリスナーが全て削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsCarousel', ['$onsen', 'CarouselView', function ($onsen, CarouselView) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. scope: false, transclude: false, compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return function (scope, element, attrs) { CustomElements.upgrade(element[0]); var carousel = new CarouselView(scope, element, attrs); element.data('ons-carousel', carousel); $onsen.registerEventHandlers(carousel, 'postchange refresh overscroll destroy'); $onsen.declareVarAttribute(attrs, carousel); scope.$on('$destroy', function () { carousel._events = undefined; element.data('ons-carousel', undefined); element = null; }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); module.directive('onsCarouselItem', function () { return { restrict: 'E', compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return function (scope, element, attrs) { CustomElements.upgrade(element[0]); }; } }; }); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-dialog */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this dialog.[/en] * [ja]このダイアログを参照するための名前を指定します。[/ja] */ /** * @attribute ons-preshow * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en] * [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-prehide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en] * [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postshow * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en] * [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-posthide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en] * [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーが指定されなかった場合には、そのイベントに紐付いているイベントリスナーが全て削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ (function () { 'use strict'; angular.module('onsen').directive('onsDialog', ['$onsen', 'DialogView', function ($onsen, DialogView) { return { restrict: 'E', scope: true, compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function pre(scope, element, attrs) { CustomElements.upgrade(element[0]); var dialog = new DialogView(scope, element, attrs); $onsen.declareVarAttribute(attrs, dialog); $onsen.registerEventHandlers(dialog, 'preshow prehide postshow posthide destroy'); $onsen.addModifierMethodsForCustomElements(dialog, element); element.data('ons-dialog', dialog); scope.$on('$destroy', function () { dialog._events = undefined; $onsen.removeModifierMethods(dialog); element.data('ons-dialog', undefined); element = null; }); }, post: function post(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsDummyForInit', ['$rootScope', function ($rootScope) { var isReady = false; return { restrict: 'E', replace: false, link: { post: function post(scope, element) { if (!isReady) { isReady = true; $rootScope.$broadcast('$ons-ready'); } element.remove(); } } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; var EVENTS = ('drag dragleft dragright dragup dragdown hold release swipe swipeleft swiperight ' + 'swipeup swipedown tap doubletap touch transform pinch pinchin pinchout rotate').split(/ +/); angular.module('onsen').directive('onsGestureDetector', ['$onsen', function ($onsen) { var scopeDef = EVENTS.reduce(function (dict, name) { dict['ng' + titlize(name)] = '&'; return dict; }, {}); function titlize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } return { restrict: 'E', scope: scopeDef, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. replace: false, transclude: true, compile: function compile(element, attrs) { return function link(scope, element, attrs, _, transclude) { transclude(scope.$parent, function (cloned) { element.append(cloned); }); var handler = function handler(event) { var attr = 'ng' + titlize(event.type); if (attr in scopeDef) { scope[attr]({ $event: event }); } }; var gestureDetector; setImmediate(function () { gestureDetector = element[0]._gestureDetector; gestureDetector.on(EVENTS.join(' '), handler); }); $onsen.cleaner.onDestroy(scope, function () { gestureDetector.off(EVENTS.join(' '), handler); $onsen.clearComponent({ scope: scope, element: element, attrs: attrs }); gestureDetector.element = scope = element = attrs = null; }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-if-orientation * @category conditional * @description * [en]Conditionally display content depending on screen orientation. Valid values are portrait and landscape. Different from other components, this component is used as attribute in any element.[/en] * [ja]画面の向きに応じてコンテンツの制御を行います。portraitもしくはlandscapeを指定できます。すべての要素の属性に使用できます。[/ja] * @seealso ons-if-platform [en]ons-if-platform component[/en][ja]ons-if-platformコンポーネント[/ja] * @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja] * @example * <div ons-if-orientation="portrait"> * <p>This will only be visible in portrait mode.</p> * </div> */ /** * @attribute ons-if-orientation * @initonly * @type {String} * @description * [en]Either "portrait" or "landscape".[/en] * [ja]portraitもしくはlandscapeを指定します。[/ja] */ (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsIfOrientation', ['$onsen', '$onsGlobal', function ($onsen, $onsGlobal) { return { restrict: 'A', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: false, compile: function compile(element) { element.css('display', 'none'); return function (scope, element, attrs) { element.addClass('ons-if-orientation-inner'); attrs.$observe('onsIfOrientation', update); $onsGlobal.orientation.on('change', update); update(); $onsen.cleaner.onDestroy(scope, function () { $onsGlobal.orientation.off('change', update); $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); element = scope = attrs = null; }); function update() { var userOrientation = ('' + attrs.onsIfOrientation).toLowerCase(); var orientation = getLandscapeOrPortrait(); if (userOrientation === 'portrait' || userOrientation === 'landscape') { if (userOrientation === orientation) { element.css('display', ''); } else { element.css('display', 'none'); } } } function getLandscapeOrPortrait() { return $onsGlobal.orientation.isPortrait() ? 'portrait' : 'landscape'; } }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-if-platform * @category conditional * @description * [en]Conditionally display content depending on the platform / browser. Valid values are "opera", "firefox", "safari", "chrome", "ie", "edge", "android", "blackberry", "ios" and "wp".[/en] * [ja]プラットフォームやブラウザーに応じてコンテンツの制御をおこないます。opera, firefox, safari, chrome, ie, edge, android, blackberry, ios, wpのいずれかの値を空白区切りで複数指定できます。[/ja] * @seealso ons-if-orientation [en]ons-if-orientation component[/en][ja]ons-if-orientationコンポーネント[/ja] * @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja] * @example * <div ons-if-platform="android"> * ... * </div> */ /** * @attribute ons-if-platform * @type {String} * @initonly * @description * [en]One or multiple space separated values: "opera", "firefox", "safari", "chrome", "ie", "edge", "android", "blackberry", "ios" or "wp".[/en] * [ja]"opera", "firefox", "safari", "chrome", "ie", "edge", "android", "blackberry", "ios", "wp"のいずれか空白区切りで複数指定できます。[/ja] */ (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsIfPlatform', ['$onsen', function ($onsen) { return { restrict: 'A', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: false, compile: function compile(element) { element.addClass('ons-if-platform-inner'); element.css('display', 'none'); var platform = getPlatformString(); return function (scope, element, attrs) { attrs.$observe('onsIfPlatform', function (userPlatform) { if (userPlatform) { update(); } }); update(); $onsen.cleaner.onDestroy(scope, function () { $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); element = scope = attrs = null; }); function update() { var userPlatforms = attrs.onsIfPlatform.toLowerCase().trim().split(/\s+/); if (userPlatforms.indexOf(platform.toLowerCase()) >= 0) { element.css('display', 'block'); } else { element.css('display', 'none'); } } }; function getPlatformString() { if (navigator.userAgent.match(/Android/i)) { return 'android'; } if (navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/RIM Tablet OS/i) || navigator.userAgent.match(/BB10/i)) { return 'blackberry'; } if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) { return 'ios'; } if (navigator.userAgent.match(/Windows Phone|IEMobile|WPDesktop/i)) { return 'wp'; } // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera) var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; if (isOpera) { return 'opera'; } var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+ if (isFirefox) { return 'firefox'; } var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; // At least Safari 3+: "[object HTMLElementConstructor]" if (isSafari) { return 'safari'; } var isEdge = navigator.userAgent.indexOf(' Edge/') >= 0; if (isEdge) { return 'edge'; } var isChrome = !!window.chrome && !isOpera && !isEdge; // Chrome 1+ if (isChrome) { return 'chrome'; } var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6 if (isIE) { return 'ie'; } return 'unknown'; } } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @ngdoc directive * @id input * @name ons-input * @category form * @description * [en]Input component.[/en] * [ja]inputコンポ―ネントです。[/ja] * @codepen ojQxLj * @guide UsingFormComponents * [en]Using form components[/en] * [ja]フォームを使う[/ja] * @guide EventHandling * [en]Event handling descriptions[/en] * [ja]イベント処理の使い方[/ja] * @example * <ons-input></ons-input> * <ons-input modifier="material" label="Username"></ons-input> */ /** * @ngdoc attribute * @name label * @type {String} * @description * [en]Text for animated floating label.[/en] * [ja]アニメーションさせるフローティングラベルのテキストを指定します。[/ja] */ /** * @ngdoc attribute * @name float * @description * [en]If this attribute is present, the label will be animated.[/en] * [ja]この属性が設定された時、ラベルはアニメーションするようになります。[/ja] */ /** * @ngdoc attribute * @name ng-model * @extensionOf angular * @description * [en]Bind the value to a model. Works just like for normal input elements.[/en] * [ja]この要素の値をモデルに紐付けます。通常のinput要素の様に動作します。[/ja] */ /** * @ngdoc attribute * @name ng-change * @extensionOf angular * @description * [en]Executes an expression when the value changes. Works just like for normal input elements.[/en] * [ja]値が変わった時にこの属性で指定したexpressionが実行されます。通常のinput要素の様に動作します。[/ja] */ (function () { 'use strict'; angular.module('onsen').directive('onsInput', ['$parse', function ($parse) { return { restrict: 'E', replace: false, scope: false, link: function link(scope, element, attrs) { CustomElements.upgrade(element[0]); var el = element[0]; var onInput = function onInput() { var set = $parse(attrs.ngModel).assign; if (el._isTextInput) { set(scope, el.value); } else if (el.type === 'radio' && el.checked) { set(scope, el.value); } else { set(scope, el.checked); } if (attrs.ngChange) { scope.$eval(attrs.ngChange); } scope.$parent.$evalAsync(); }; if (attrs.ngModel) { scope.$watch(attrs.ngModel, function (value) { if (el._isTextInput) { el.value = value; } else if (el.type === 'radio') { el.checked = value === el.value; } else { el.checked = value; } }); el._isTextInput ? element.on('input', onInput) : element.on('change', onInput); } scope.$on('$destroy', function () { el._isTextInput ? element.off('input', onInput) : element.off('change', onInput); scope = element = attrs = el = null; }); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-keyboard-active * @category form * @description * [en] * Conditionally display content depending on if the software keyboard is visible or hidden. * This component requires cordova and that the com.ionic.keyboard plugin is installed. * [/en] * [ja] * ソフトウェアキーボードが表示されているかどうかで、コンテンツを表示するかどうかを切り替えることが出来ます。 * このコンポーネントは、Cordovaやcom.ionic.keyboardプラグインを必要とします。 * [/ja] * @guide UtilityAPIs * [en]Other utility APIs[/en] * [ja]他のユーティリティAPI[/ja] * @example * <div ons-keyboard-active> * This will only be displayed if the software keyboard is open. * </div> * <div ons-keyboard-inactive> * There is also a component that does the opposite. * </div> */ /** * @attribute ons-keyboard-active * @description * [en]The content of tags with this attribute will be visible when the software keyboard is open.[/en] * [ja]この属性がついた要素は、ソフトウェアキーボードが表示された時に初めて表示されます。[/ja] */ /** * @attribute ons-keyboard-inactive * @description * [en]The content of tags with this attribute will be visible when the software keyboard is hidden.[/en] * [ja]この属性がついた要素は、ソフトウェアキーボードが隠れている時のみ表示されます。[/ja] */ (function () { 'use strict'; var module = angular.module('onsen'); var compileFunction = function compileFunction(show, $onsen) { return function (element) { return function (scope, element, attrs) { var dispShow = show ? 'block' : 'none', dispHide = show ? 'none' : 'block'; var onShow = function onShow() { element.css('display', dispShow); }; var onHide = function onHide() { element.css('display', dispHide); }; var onInit = function onInit(e) { if (e.visible) { onShow(); } else { onHide(); } }; ons.softwareKeyboard.on('show', onShow); ons.softwareKeyboard.on('hide', onHide); ons.softwareKeyboard.on('init', onInit); if (ons.softwareKeyboard._visible) { onShow(); } else { onHide(); } $onsen.cleaner.onDestroy(scope, function () { ons.softwareKeyboard.off('show', onShow); ons.softwareKeyboard.off('hide', onHide); ons.softwareKeyboard.off('init', onInit); $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); element = scope = attrs = null; }); }; }; }; module.directive('onsKeyboardActive', ['$onsen', function ($onsen) { return { restrict: 'A', replace: false, transclude: false, scope: false, compile: compileFunction(true, $onsen) }; }]); module.directive('onsKeyboardInactive', ['$onsen', function ($onsen) { return { restrict: 'A', replace: false, transclude: false, scope: false, compile: compileFunction(false, $onsen) }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-lazy-repeat * @description * [en] * Using this component a list with millions of items can be rendered without a drop in performance. * It does that by "lazily" loading elements into the DOM when they come into view and * removing items from the DOM when they are not visible. * [/en] * [ja] * このコンポーネント内で描画されるアイテムのDOM要素の読み込みは、画面に見えそうになった時まで自動的に遅延され、 * 画面から見えなくなった場合にはその要素は動的にアンロードされます。 * このコンポーネントを使うことで、パフォーマンスを劣化させること無しに巨大な数の要素を描画できます。 * [/ja] * @codepen QwrGBm * @guide UsingLazyRepeat * [en]How to use Lazy Repeat[/en] * [ja]レイジーリピートの使い方[/ja] * @example * <script> * ons.bootstrap() * * .controller('MyController', function($scope) { * $scope.MyDelegate = { * countItems: function() { * // Return number of items. * return 1000000; * }, * * calculateItemHeight: function(index) { * // Return the height of an item in pixels. * return 45; * }, * * configureItemScope: function(index, itemScope) { * // Initialize scope * itemScope.item = 'Item #' + (index + 1); * }, * * destroyItemScope: function(index, itemScope) { * // Optional method that is called when an item is unloaded. * console.log('Destroyed item with index: ' + index); * } * }; * }); * </script> * * <ons-list ng-controller="MyController"> * <ons-list-item ons-lazy-repeat="MyDelegate"> * {{ item }} * </ons-list-item> * </ons-list> */ /** * @attribute ons-lazy-repeat * @type {Expression} * @initonly * @description * [en]A delegate object, can be either an object attached to the scope (when using AngularJS) or a normal JavaScript variable.[/en] * [ja]要素のロード、アンロードなどの処理を委譲するオブジェクトを指定します。AngularJSのスコープの変数名や、通常のJavaScriptの変数名を指定します。[/ja] */ /** * @property delegate.configureItemScope * @type {Function} * @description * [en]Function which recieves an index and the scope for the item. Can be used to configure values in the item scope.[/en] * [ja][/ja] */ (function () { 'use strict'; var module = angular.module('onsen'); /** * Lazy repeat directive. */ module.directive('onsLazyRepeat', ['$onsen', 'LazyRepeatView', function ($onsen, LazyRepeatView) { return { restrict: 'A', replace: false, priority: 1000, terminal: true, compile: function compile(element, attrs) { return function (scope, element, attrs) { var lazyRepeat = new LazyRepeatView(scope, element, attrs); scope.$on('$destroy', function () { scope = element = attrs = lazyRepeat = null; }); }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; angular.module('onsen').directive('onsList', ['$onsen', 'GenericView', function ($onsen, GenericView) { return { restrict: 'E', link: function link(scope, element, attrs) { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, { viewKey: 'ons-list' }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; angular.module('onsen').directive('onsListHeader', ['$onsen', 'GenericView', function ($onsen, GenericView) { return { restrict: 'E', link: function link(scope, element, attrs) { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, { viewKey: 'ons-listHeader' }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; angular.module('onsen').directive('onsListItem', ['$onsen', 'GenericView', function ($onsen, GenericView) { return { restrict: 'E', link: function link(scope, element, attrs) { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, { viewKey: 'ons-list-item' }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-loading-placeholder * @category util * @description * [en]Display a placeholder while the content is loading.[/en] * [ja]Onsen UIが読み込まれるまでに表示するプレースホルダーを表現します。[/ja] * @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja] * @example * <div ons-loading-placeholder="page.html"> * Loading... * </div> */ /** * @attribute ons-loading-placeholder * @initonly * @type {String} * @description * [en]The url of the page to load.[/en] * [ja]読み込むページのURLを指定します。[/ja] */ (function () { 'use strict'; angular.module('onsen').directive('onsLoadingPlaceholder', function () { return { restrict: 'A', link: function link(scope, element, attrs) { CustomElements.upgrade(element[0]); if (attrs.onsLoadingPlaceholder) { ons._resolveLoadingPlaceholder(element[0], attrs.onsLoadingPlaceholder, function (contentElement, done) { CustomElements.upgrade(contentElement); ons.compile(contentElement); scope.$evalAsync(function () { setImmediate(done); }); }); } } }; }); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-modal */ /** * @attribute var * @type {String} * @initonly * @description * [en]Variable name to refer this modal.[/en] * [ja]このモーダルを参照するための名前を指定します。[/ja] */ (function () { 'use strict'; /** * Modal directive. */ angular.module('onsen').directive('onsModal', ['$onsen', 'ModalView', function ($onsen, ModalView) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. scope: false, transclude: false, link: { pre: function pre(scope, element, attrs) { CustomElements.upgrade(element[0]); var modal = new ModalView(scope, element, attrs); $onsen.addModifierMethodsForCustomElements(modal, element); $onsen.declareVarAttribute(attrs, modal); element.data('ons-modal', modal); element[0]._ensureNodePosition(); scope.$on('$destroy', function () { $onsen.removeModifierMethods(modal); element.data('ons-modal', undefined); modal = element = scope = attrs = null; }); }, post: function post(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-navigator * @example * <ons-navigator animation="slide" var="app.navi"> * <ons-page> * <ons-toolbar> * <div class="center">Title</div> * </ons-toolbar> * * <p style="text-align: center"> * <ons-button modifier="light" ng-click="app.navi.pushPage('page.html');">Push</ons-button> * </p> * </ons-page> * </ons-navigator> * * <ons-template id="page.html"> * <ons-page> * <ons-toolbar> * <div class="center">Title</div> * </ons-toolbar> * * <p style="text-align: center"> * <ons-button modifier="light" ng-click="app.navi.popPage();">Pop</ons-button> * </p> * </ons-page> * </ons-template> */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this navigator.[/en] * [ja]このナビゲーターを参照するための名前を指定します。[/ja] */ /** * @attribute ons-prepush * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prepush" event is fired.[/en] * [ja]"prepush"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-prepop * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prepop" event is fired.[/en] * [ja]"prepop"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postpush * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postpush" event is fired.[/en] * [ja]"postpush"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postpop * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postpop" event is fired.[/en] * [ja]"postpop"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-init * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "init" event is fired.[/en] * [ja]ページの"init"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-show * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "show" event is fired.[/en] * [ja]ページの"show"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-hide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "hide" event is fired.[/en] * [ja]ページの"hide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "destroy" event is fired.[/en] * [ja]ページの"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function () { 'use strict'; var lastReady = window.OnsNavigatorElement.rewritables.ready; window.OnsNavigatorElement.rewritables.ready = ons._waitDiretiveInit('ons-navigator', lastReady); var lastLink = window.OnsNavigatorElement.rewritables.link; window.OnsNavigatorElement.rewritables.link = function (navigatorElement, target, options, callback) { var view = angular.element(navigatorElement).data('ons-navigator'); view._compileAndLink(target, function (target) { lastLink(navigatorElement, target, options, callback); }); }; angular.module('onsen').directive('onsNavigator', ['NavigatorView', '$onsen', function (NavigatorView, $onsen) { return { restrict: 'E', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: true, compile: function compile(element) { CustomElements.upgrade(element[0]); return { pre: function pre(scope, element, attrs, controller) { CustomElements.upgrade(element[0]); var navigator = new NavigatorView(scope, element, attrs); $onsen.declareVarAttribute(attrs, navigator); $onsen.registerEventHandlers(navigator, 'prepush prepop postpush postpop init show hide destroy'); element.data('ons-navigator', navigator); scope.$on('$destroy', function () { navigator._events = undefined; element.data('ons-navigator', undefined); element = null; }); }, post: function post(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-page */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this page.[/en] * [ja]このページを参照するための名前を指定します。[/ja] */ /** * @attribute ng-infinite-scroll * @initonly * @type {String} * @description * [en]Path of the function to be executed on infinite scrolling. The path is relative to $scope. The function receives a done callback that must be called when it's finished.[/en] * [ja][/ja] */ /** * @attribute on-device-back-button * @type {Expression} * @description * [en]Allows you to specify custom behavior when the back button is pressed.[/en] * [ja]デバイスのバックボタンが押された時の挙動を設定できます。[/ja] */ /** * @attribute ng-device-back-button * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior with an AngularJS expression when the back button is pressed.[/en] * [ja]デバイスのバックボタンが押された時の挙動を設定できます。AngularJSのexpressionを指定できます。[/ja] */ /** * @attribute ons-init * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "init" event is fired.[/en] * [ja]"init"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-show * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "show" event is fired.[/en] * [ja]"show"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-hide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "hide" event is fired.[/en] * [ja]"hide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsPage', ['$onsen', 'PageView', function ($onsen, PageView) { function firePageInitEvent(element) { // TODO: remove dirty fix var i = 0, f = function f() { if (i++ < 15) { if (isAttached(element)) { $onsen.fireComponentEvent(element, 'init'); fireActualPageInitEvent(element); } else { if (i > 10) { setTimeout(f, 1000 / 60); } else { setImmediate(f); } } } else { throw new Error('Fail to fire "pageinit" event. Attach "ons-page" element to the document after initialization.'); } }; f(); } function fireActualPageInitEvent(element) { var event = document.createEvent('HTMLEvents'); event.initEvent('pageinit', true, true); element.dispatchEvent(event); } function isAttached(element) { if (document.documentElement === element) { return true; } return element.parentNode ? isAttached(element.parentNode) : false; } return { restrict: 'E', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: true, compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function pre(scope, element, attrs) { CustomElements.upgrade(element[0]); var page = new PageView(scope, element, attrs); $onsen.declareVarAttribute(attrs, page); $onsen.registerEventHandlers(page, 'init show hide destroy'); element.data('ons-page', page); $onsen.addModifierMethodsForCustomElements(page, element); element.data('_scope', scope); $onsen.cleaner.onDestroy(scope, function () { page._events = undefined; $onsen.removeModifierMethods(page); element.data('ons-page', undefined); element.data('_scope', undefined); $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); scope = element = attrs = null; }); }, post: function postLink(scope, element, attrs) { firePageInitEvent(element[0]); } }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-popover */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this popover.[/en] * [ja]このポップオーバーを参照するための名前を指定します。[/ja] */ /** * @attribute ons-preshow * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en] * [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-prehide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en] * [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postshow * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en] * [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-posthide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en] * [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsPopover', ['$onsen', 'PopoverView', function ($onsen, PopoverView) { return { restrict: 'E', replace: false, scope: true, compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function pre(scope, element, attrs) { CustomElements.upgrade(element[0]); var popover = new PopoverView(scope, element, attrs); $onsen.declareVarAttribute(attrs, popover); $onsen.registerEventHandlers(popover, 'preshow prehide postshow posthide destroy'); $onsen.addModifierMethodsForCustomElements(popover, element); element.data('ons-popover', popover); scope.$on('$destroy', function () { popover._events = undefined; $onsen.removeModifierMethods(popover); element.data('ons-popover', undefined); element = null; }); }, post: function post(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-pull-hook * @example * <script> * ons.bootstrap() * * .controller('MyController', function($scope, $timeout) { * $scope.items = [3, 2 ,1]; * * $scope.load = function($done) { * $timeout(function() { * $scope.items.unshift($scope.items.length + 1); * $done(); * }, 1000); * }; * }); * </script> * * <ons-page ng-controller="MyController"> * <ons-pull-hook var="loader" ng-action="load($done)"> * <span ng-switch="loader.state"> * <span ng-switch-when="initial">Pull down to refresh</span> * <span ng-switch-when="preaction">Release to refresh</span> * <span ng-switch-when="action">Loading data. Please wait...</span> * </span> * </ons-pull-hook> * <ons-list> * <ons-list-item ng-repeat="item in items"> * Item #{{ item }} * </ons-list-item> * </ons-list> * </ons-page> */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this component.[/en] * [ja]このコンポーネントを参照するための名前を指定します。[/ja] */ /** * @attribute ng-action * @initonly * @type {Expression} * @description * [en]Use to specify custom behavior when the page is pulled down. A <code>$done</code> function is available to tell the component that the action is completed.[/en] * [ja]pull downしたときの振る舞いを指定します。アクションが完了した時には<code>$done</code>関数を呼び出します。[/ja] */ /** * @attribute ons-changestate * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "changestate" event is fired.[/en] * [ja]"changestate"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function () { 'use strict'; /** * Pull hook directive. */ angular.module('onsen').directive('onsPullHook', ['$onsen', 'PullHookView', function ($onsen, PullHookView) { return { restrict: 'E', replace: false, scope: true, compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return { pre: function pre(scope, element, attrs) { CustomElements.upgrade(element[0]); var pullHook = new PullHookView(scope, element, attrs); $onsen.declareVarAttribute(attrs, pullHook); $onsen.registerEventHandlers(pullHook, 'changestate destroy'); element.data('ons-pull-hook', pullHook); scope.$on('$destroy', function () { pullHook._events = undefined; element.data('ons-pull-hook', undefined); scope = element = attrs = null; }); }, post: function post(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; angular.module('onsen').directive('onsRange', ['$parse', function ($parse) { return { restrict: 'E', replace: false, scope: false, link: function link(scope, element, attrs) { CustomElements.upgrade(element[0]); var onInput = function onInput() { var set = $parse(attrs.ngModel).assign; set(scope, element[0].value); if (attrs.ngChange) { scope.$eval(attrs.ngChange); } scope.$parent.$evalAsync(); }; if (attrs.ngModel) { scope.$watch(attrs.ngModel, function (value) { element[0].value = value; }); element.on('input', onInput); } scope.$on('$destroy', function () { element.off('input', onInput); scope = element = attrs = null; }); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; angular.module('onsen').directive('onsRipple', ['$onsen', 'GenericView', function ($onsen, GenericView) { return { restrict: 'E', link: function link(scope, element, attrs) { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, { viewKey: 'ons-ripple' }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-scope * @category util * @description * [en]All child elements using the "var" attribute will be attached to the scope of this element.[/en] * [ja]"var"属性を使っている全ての子要素のviewオブジェクトは、この要素のAngularJSスコープに追加されます。[/ja] * @example * <ons-list> * <ons-list-item ons-scope ng-repeat="item in items"> * <ons-carousel var="carousel"> * <ons-carousel-item ng-click="carousel.next()"> * {{ item }} * </ons-carousel-item> * </ons-carousel-item ng-click="carousel.prev()"> * ... * </ons-carousel-item> * </ons-carousel> * </ons-list-item> * </ons-list> */ (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsScope', ['$onsen', function ($onsen) { return { restrict: 'A', replace: false, transclude: false, scope: false, link: function link(scope, element) { element.data('_scope', scope); scope.$on('$destroy', function () { element.data('_scope', undefined); }); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-sliding-menu * @category sliding-menu * @description * [en]Component for sliding UI where one page is overlayed over another page. The above page can be slided aside to reveal the page behind.[/en] * [ja]スライディングメニューを表現するためのコンポーネントで、片方のページが別のページの上にオーバーレイで表示されます。above-pageで指定されたページは、横からスライドして表示します。[/ja] * @codepen IDvFJ * @seealso ons-page * [en]ons-page component[/en] * [ja]ons-pageコンポーネント[/ja] * @guide UsingSlidingMenu * [en]Using sliding menu[/en] * [ja]スライディングメニューを使う[/ja] * @guide EventHandling * [en]Using events[/en] * [ja]イベントの利用[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @example * <ons-sliding-menu var="app.menu" main-page="page.html" menu-page="menu.html" max-slide-distance="200px" type="reveal" side="left"> * </ons-sliding-menu> * * <ons-template id="page.html"> * <ons-page> * <p style="text-align: center"> * <ons-button ng-click="app.menu.toggleMenu()">Toggle</ons-button> * </p> * </ons-page> * </ons-template> * * <ons-template id="menu.html"> * <ons-page> * <!-- menu page's contents --> * </ons-page> * </ons-template> * */ /** * @event preopen * @description * [en]Fired just before the sliding menu is opened.[/en] * [ja]スライディングメニューが開く前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @event postopen * @description * [en]Fired just after the sliding menu is opened.[/en] * [ja]スライディングメニューが開き終わった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @event preclose * @description * [en]Fired just before the sliding menu is closed.[/en] * [ja]スライディングメニューが閉じる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @event postclose * @description * [en]Fired just after the sliding menu is closed.[/en] * [ja]スライディングメニューが閉じ終わった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this sliding menu.[/en] * [ja]このスライディングメニューを参照するための名前を指定します。[/ja] */ /** * @attribute menu-page * @initonly * @type {String} * @description * [en]The url of the menu page.[/en] * [ja]左に位置するメニューページのURLを指定します。[/ja] */ /** * @attribute main-page * @initonly * @type {String} * @description * [en]The url of the main page.[/en] * [ja]右に位置するメインページのURLを指定します。[/ja] */ /** * @attribute swipeable * @initonly * @type {Boolean} * @description * [en]Whether to enable swipe interaction.[/en] * [ja]スワイプ操作を有効にする場合に指定します。[/ja] */ /** * @attribute swipe-target-width * @initonly * @type {String} * @description * [en]The width of swipeable area calculated from the left (in pixels). Use this to enable swipe only when the finger touch on the screen edge.[/en] * [ja]スワイプの判定領域をピクセル単位で指定します。画面の端から指定した距離に達するとページが表示されます。[/ja] */ /** * @attribute max-slide-distance * @initonly * @type {String} * @description * [en]How far the menu page will slide open. Can specify both in px and %. eg. 90%, 200px[/en] * [ja]menu-pageで指定されたページの表示幅を指定します。ピクセルもしくは%の両方で指定できます(例: 90%, 200px)[/ja] */ /** * @attribute side * @initonly * @type {String} * @description * [en]Specify which side of the screen the menu page is located on. Possible values are "left" and "right".[/en] * [ja]menu-pageで指定されたページが画面のどちら側から表示されるかを指定します。leftもしくはrightのいずれかを指定できます。[/ja] */ /** * @attribute type * @initonly * @type {String} * @description * [en]Sliding menu animator. Possible values are reveal (default), push and overlay.[/en] * [ja]スライディングメニューのアニメーションです。"reveal"(デフォルト)、"push"、"overlay"のいずれかを指定できます。[/ja] */ /** * @attribute ons-preopen * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preopen" event is fired.[/en] * [ja]"preopen"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-preclose * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preclose" event is fired.[/en] * [ja]"preclose"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postopen * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postopen" event is fired.[/en] * [ja]"postopen"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postclose * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postclose" event is fired.[/en] * [ja]"postclose"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-init * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "init" event is fired.[/en] * [ja]ページの"init"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-show * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "show" event is fired.[/en] * [ja]ページの"show"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-hide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "hide" event is fired.[/en] * [ja]ページの"hide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "destroy" event is fired.[/en] * [ja]ページの"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @method setMainPage * @signature setMainPage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Boolean} [options.closeMenu] * [en]If true the menu will be closed.[/en] * [ja]trueを指定すると、開いているメニューを閉じます。[/ja] * @param {Function} [options.callback] * [en]Function that is executed after the page has been set.[/en] * [ja]ページが読み込まれた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the main contents pane.[/en] * [ja]中央部分に表示されるページをpageUrlに指定します。[/ja] */ /** * @method setMenuPage * @signature setMenuPage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Boolean} [options.closeMenu] * [en]If true the menu will be closed after the menu page has been set.[/en] * [ja]trueを指定すると、開いているメニューを閉じます。[/ja] * @param {Function} [options.callback] * [en]This function will be executed after the menu page has been set.[/en] * [ja]メニューページが読み込まれた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the side menu pane.[/en] * [ja]メニュー部分に表示されるページをpageUrlに指定します。[/ja] */ /** * @method openMenu * @signature openMenu([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been opened.[/en] * [ja]メニューが開いた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Slide the above layer to reveal the layer behind.[/en] * [ja]メニューページを表示します。[/ja] */ /** * @method closeMenu * @signature closeMenu([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been closed.[/en] * [ja]メニューが閉じられた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Slide the above layer to hide the layer behind.[/en] * [ja]メニューページを非表示にします。[/ja] */ /** * @method toggleMenu * @signature toggleMenu([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been opened or closed.[/en] * [ja]メニューが開き終わった後か、閉じ終わった後に呼び出される関数オブジェクトです。[/ja] * @description * [en]Slide the above layer to reveal the layer behind if it is currently hidden, otherwise, hide the layer behind.[/en] * [ja]現在の状況に合わせて、メニューページを表示もしくは非表示にします。[/ja] */ /** * @method isMenuOpened * @signature isMenuOpened() * @return {Boolean} * [en]true if the menu is currently open.[/en] * [ja]メニューが開いていればtrueとなります。[/ja] * @description * [en]Returns true if the menu page is open, otherwise false.[/en] * [ja]メニューページが開いている場合はtrue、そうでない場合はfalseを返します。[/ja] */ /** * @method getDeviceBackButtonHandler * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Retrieve the back-button handler.[/en] * [ja]ons-sliding-menuに紐付いているバックボタンハンドラを取得します。[/ja] */ /** * @method setSwipeable * @signature setSwipeable(swipeable) * @param {Boolean} swipeable * [en]If true the menu will be swipeable.[/en] * [ja]スワイプで開閉できるようにする場合にはtrueを指定します。[/ja] * @description * [en]Specify if the menu should be swipeable or not.[/en] * [ja]スワイプで開閉するかどうかを設定する。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsSlidingMenu', ['$compile', 'SlidingMenuView', '$onsen', function ($compile, SlidingMenuView, $onsen) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: true, compile: function compile(element, attrs) { var main = element[0].querySelector('.main'), menu = element[0].querySelector('.menu'); if (main) { var mainHtml = angular.element(main).remove().html().trim(); } if (menu) { var menuHtml = angular.element(menu).remove().html().trim(); } return function (scope, element, attrs) { element.append(angular.element('<div></div>').addClass('onsen-sliding-menu__menu ons-sliding-menu-inner')); element.append(angular.element('<div></div>').addClass('onsen-sliding-menu__main ons-sliding-menu-inner')); var slidingMenu = new SlidingMenuView(scope, element, attrs); $onsen.registerEventHandlers(slidingMenu, 'preopen preclose postopen postclose init show hide destroy'); if (mainHtml && !attrs.mainPage) { slidingMenu._appendMainPage(null, mainHtml); } if (menuHtml && !attrs.menuPage) { slidingMenu._appendMenuPage(menuHtml); } $onsen.declareVarAttribute(attrs, slidingMenu); element.data('ons-sliding-menu', slidingMenu); scope.$on('$destroy', function () { slidingMenu._events = undefined; element.data('ons-sliding-menu', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-split-view * @category split-view * @description * [en]Divides the screen into a left and right section.[/en] * [ja]画面を左右に分割するコンポーネントです。[/ja] * @codepen nKqfv {wide} * @guide Usingonssplitviewcomponent * [en]Using ons-split-view.[/en] * [ja]ons-split-viewコンポーネントを使う[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @example * <ons-split-view * secondary-page="secondary.html" * main-page="main.html" * main-page-width="70%" * collapse="portrait"> * </ons-split-view> */ /** * @event update * @description * [en]Fired when the split view is updated.[/en] * [ja]split viewの状態が更新された際に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Boolean} event.shouldCollapse * [en]True if the view should collapse.[/en] * [ja]collapse状態の場合にtrueになります。[/ja] * @param {String} event.currentMode * [en]Current mode.[/en] * [ja]現在のモード名を返します。"collapse"か"split"かのいずれかです。[/ja] * @param {Function} event.split * [en]Call to force split.[/en] * [ja]この関数を呼び出すと強制的にsplitモードにします。[/ja] * @param {Function} event.collapse * [en]Call to force collapse.[/en] * [ja]この関数を呼び出すと強制的にcollapseモードにします。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewの幅を返します。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"かもしくは"landscape"です。 [/ja] */ /** * @event presplit * @description * [en]Fired just before the view is split.[/en] * [ja]split状態にる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @event postsplit * @description * [en]Fired just after the view is split.[/en] * [ja]split状態になった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @event precollapse * @description * [en]Fired just before the view is collapsed.[/en] * [ja]collapse状態になる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @event postcollapse * @description * [en]Fired just after the view is collapsed.[/en] * [ja]collapse状態になった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this split view.[/en] * [ja]このスプリットビューコンポーネントを参照するための名前を指定します。[/ja] */ /** * @attribute main-page * @initonly * @type {String} * @description * [en]The url of the page on the right.[/en] * [ja]右側に表示するページのURLを指定します。[/ja] */ /** * @attribute main-page-width * @initonly * @type {Number} * @description * [en]Main page width percentage. The secondary page width will be the remaining percentage.[/en] * [ja]右側のページの幅をパーセント単位で指定します。[/ja] */ /** * @attribute secondary-page * @initonly * @type {String} * @description * [en]The url of the page on the left.[/en] * [ja]左側に表示するページのURLを指定します。[/ja] */ /** * @attribute collapse * @initonly * @type {String} * @description * [en] * Specify the collapse behavior. Valid values are portrait, landscape, width #px or a media query. * "portrait" or "landscape" means the view will collapse when device is in landscape or portrait orientation. * "width #px" means the view will collapse when the window width is smaller than the specified #px. * If the value is a media query, the view will collapse when the media query is true. * [/en] * [ja] * 左側のページを非表示にする条件を指定します。portrait, landscape、width #pxもしくはメディアクエリの指定が可能です。 * portraitもしくはlandscapeを指定すると、デバイスの画面が縦向きもしくは横向きになった時に適用されます。 * width #pxを指定すると、画面が指定した横幅よりも短い場合に適用されます。 * メディアクエリを指定すると、指定したクエリに適合している場合に適用されます。 * [/ja] */ /** * @attribute ons-update * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "update" event is fired.[/en] * [ja]"update"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-presplit * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "presplit" event is fired.[/en] * [ja]"presplit"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-precollapse * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "precollapse" event is fired.[/en] * [ja]"precollapse"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postsplit * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postsplit" event is fired.[/en] * [ja]"postsplit"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postcollapse * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postcollapse" event is fired.[/en] * [ja]"postcollapse"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-init * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "init" event is fired.[/en] * [ja]ページの"init"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-show * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "show" event is fired.[/en] * [ja]ページの"show"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-hide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "hide" event is fired.[/en] * [ja]ページの"hide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "destroy" event is fired.[/en] * [ja]ページの"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @method setMainPage * @signature setMainPage(pageUrl) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <ons-template>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the right section[/en] * [ja]指定したURLをメインページを読み込みます。[/ja] */ /** * @method setSecondaryPage * @signature setSecondaryPage(pageUrl) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <ons-template>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the left section[/en] * [ja]指定したURLを左のページの読み込みます。[/ja] */ /** * @method update * @signature update() * @description * [en]Trigger an 'update' event and try to determine if the split behavior should be changed.[/en] * [ja]splitモードを変えるべきかどうかを判断するための'update'イベントを発火します。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsSplitView', ['$compile', 'SplitView', '$onsen', function ($compile, SplitView, $onsen) { return { restrict: 'E', replace: false, transclude: false, scope: true, compile: function compile(element, attrs) { var mainPage = element[0].querySelector('.main-page'), secondaryPage = element[0].querySelector('.secondary-page'); if (mainPage) { var mainHtml = angular.element(mainPage).remove().html().trim(); } if (secondaryPage) { var secondaryHtml = angular.element(secondaryPage).remove().html().trim(); } return function (scope, element, attrs) { element.append(angular.element('<div></div>').addClass('onsen-split-view__secondary full-screen ons-split-view-inner')); element.append(angular.element('<div></div>').addClass('onsen-split-view__main full-screen ons-split-view-inner')); var splitView = new SplitView(scope, element, attrs); if (mainHtml && !attrs.mainPage) { splitView._appendMainPage(mainHtml); } if (secondaryHtml && !attrs.secondaryPage) { splitView._appendSecondPage(secondaryHtml); } $onsen.declareVarAttribute(attrs, splitView); $onsen.registerEventHandlers(splitView, 'update presplit precollapse postsplit postcollapse init show hide destroy'); element.data('ons-split-view', splitView); scope.$on('$destroy', function () { splitView._events = undefined; element.data('ons-split-view', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-splitter */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this split view.[/en] * [ja]このスプリットビューコンポーネントを参照するための名前を指定します。[/ja] */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function () { 'use strict'; angular.module('onsen').directive('onsSplitter', ['$compile', 'Splitter', '$onsen', function ($compile, Splitter, $onsen) { return { restrict: 'E', scope: true, compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return function (scope, element, attrs) { CustomElements.upgrade(element[0]); var splitter = new Splitter(scope, element, attrs); $onsen.declareVarAttribute(attrs, splitter); $onsen.registerEventHandlers(splitter, 'destroy'); element.data('ons-splitter', splitter); scope.$on('$destroy', function () { splitter._events = undefined; element.data('ons-splitter', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-splitter-content */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ (function () { 'use strict'; var lastReady = window.OnsSplitterContentElement.rewritables.ready; window.OnsSplitterContentElement.rewritables.ready = ons._waitDiretiveInit('ons-splitter-content', lastReady); var lastLink = window.OnsSplitterContentElement.rewritables.link; window.OnsSplitterContentElement.rewritables.link = function (element, target, options, callback) { var view = angular.element(element).data('ons-splitter-content'); lastLink(element, target, options, function (target) { view._link(target, callback); }); }; angular.module('onsen').directive('onsSplitterContent', ['$compile', 'SplitterContent', '$onsen', function ($compile, SplitterContent, $onsen) { return { restrict: 'E', compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return function (scope, element, attrs) { CustomElements.upgrade(element[0]); var view = new SplitterContent(scope, element, attrs); $onsen.declareVarAttribute(attrs, view); $onsen.registerEventHandlers(view, 'destroy'); element.data('ons-splitter-content', view); scope.$on('$destroy', function () { view._events = undefined; element.data('ons-splitter-content', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-splitter-side */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-preopen * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preopen" event is fired.[/en] * [ja]"preopen"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-preclose * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preclose" event is fired.[/en] * [ja]"preclose"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postopen * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postopen" event is fired.[/en] * [ja]"postopen"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postclose * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postclose" event is fired.[/en] * [ja]"postclose"イベントが発火された時の挙動を独自に指定できます。[/ja] */ (function () { 'use strict'; var lastReady = window.OnsSplitterSideElement.rewritables.ready; window.OnsSplitterSideElement.rewritables.ready = ons._waitDiretiveInit('ons-splitter-side', lastReady); var lastLink = window.OnsSplitterSideElement.rewritables.link; window.OnsSplitterSideElement.rewritables.link = function (element, target, options, callback) { var view = angular.element(element).data('ons-splitter-side'); lastLink(element, target, options, function (target) { view._link(target, callback); }); }; angular.module('onsen').directive('onsSplitterSide', ['$compile', 'SplitterSide', '$onsen', function ($compile, SplitterSide, $onsen) { return { restrict: 'E', compile: function compile(element, attrs) { CustomElements.upgrade(element[0]); return function (scope, element, attrs) { CustomElements.upgrade(element[0]); var view = new SplitterSide(scope, element, attrs); $onsen.declareVarAttribute(attrs, view); $onsen.registerEventHandlers(view, 'destroy'); element.data('ons-splitter-side', view); scope.$on('$destroy', function () { view._events = undefined; element.data('ons-splitter-side', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-switch */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this switch.[/en] * [ja]JavaScriptから参照するための変数名を指定します。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function () { 'use strict'; angular.module('onsen').directive('onsSwitch', ['$onsen', 'SwitchView', function ($onsen, SwitchView) { return { restrict: 'E', replace: false, scope: true, link: function link(scope, element, attrs) { CustomElements.upgrade(element[0]); if (attrs.ngController) { throw new Error('This element can\'t accept ng-controller directive.'); } var switchView = new SwitchView(element, scope, attrs); $onsen.addModifierMethodsForCustomElements(switchView, element); $onsen.declareVarAttribute(attrs, switchView); element.data('ons-switch', switchView); $onsen.cleaner.onDestroy(scope, function () { switchView._events = undefined; $onsen.removeModifierMethods(switchView); element.data('ons-switch', undefined); $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); element = attrs = scope = null; }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; tab.$inject = ['$onsen']; angular.module('onsen').directive('onsTab', tab).directive('onsTabbarItem', tab); // for BC function tab($onsen) { return { restrict: 'E', link: function link(scope, element, attrs) { CustomElements.upgrade(element[0]); $onsen.fireComponentEvent(element[0], 'init'); } }; } })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-tabbar */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this tab bar.[/en] * [ja]このタブバーを参照するための名前を指定します。[/ja] */ /** * @attribute hide-tabs * @initonly * @type {Boolean} * @default false * @description * [en]Whether to hide the tabs. Valid values are true/false.[/en] * [ja]タブを非表示にする場合に指定します。trueもしくはfalseを指定できます。[/ja] */ /** * @attribute ons-reactive * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "reactive" event is fired.[/en] * [ja]"reactive"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-prechange * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prechange" event is fired.[/en] * [ja]"prechange"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-postchange * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postchange" event is fired.[/en] * [ja]"postchange"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-init * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "init" event is fired.[/en] * [ja]ページの"init"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-show * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "show" event is fired.[/en] * [ja]ページの"show"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-hide * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "hide" event is fired.[/en] * [ja]ページの"hide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @attribute ons-destroy * @initonly * @type {Expression} * @description * [en]Allows you to specify custom behavior when a page's "destroy" event is fired.[/en] * [ja]ページの"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @method on * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method once * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @method off * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function () { 'use strict'; var lastReady = window.OnsTabbarElement.rewritables.ready; window.OnsTabbarElement.rewritables.ready = ons._waitDiretiveInit('ons-tabbar', lastReady); var lastLink = window.OnsTabbarElement.rewritables.link; window.OnsTabbarElement.rewritables.link = function (tabbarElement, target, options, callback) { var view = angular.element(tabbarElement).data('ons-tabbar'); view._compileAndLink(target, function (target) { lastLink(tabbarElement, target, options, callback); }); }; var lastUnlink = window.OnsTabbarElement.rewritables.unlink; window.OnsTabbarElement.rewritables.unlink = function (tabbarElement, target, callback) { angular.element(target).data('_scope').$destroy(); lastUnlink(tabbarElement, target, callback); }; angular.module('onsen').directive('onsTabbar', ['$onsen', '$compile', '$parse', 'TabbarView', function ($onsen, $compile, $parse, TabbarView) { return { restrict: 'E', replace: false, scope: true, link: function link(scope, element, attrs, controller) { CustomElements.upgrade(element[0]); scope.$watch(attrs.hideTabs, function (hide) { if (typeof hide === 'string') { hide = hide === 'true'; } element[0].setTabbarVisibility(!hide); }); var tabbarView = new TabbarView(scope, element, attrs); $onsen.addModifierMethodsForCustomElements(tabbarView, element); $onsen.registerEventHandlers(tabbarView, 'reactive prechange postchange init show hide destroy'); element.data('ons-tabbar', tabbarView); $onsen.declareVarAttribute(attrs, tabbarView); scope.$on('$destroy', function () { tabbarView._events = undefined; $onsen.removeModifierMethods(tabbarView); element.data('ons-tabbar', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; (function () { 'use strict'; angular.module('onsen').directive('onsTemplate', ['$templateCache', function ($templateCache) { return { restrict: 'E', terminal: true, compile: function compile(element) { CustomElements.upgrade(element[0]); var content = element[0].template || element.html(); $templateCache.put(element.attr('id'), content); } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-toolbar */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this toolbar.[/en] * [ja]このツールバーを参照するための名前を指定します。[/ja] */ (function () { 'use strict'; angular.module('onsen').directive('onsToolbar', ['$onsen', 'GenericView', function ($onsen, GenericView) { return { restrict: 'E', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. scope: false, transclude: false, compile: function compile(element) { CustomElements.upgrade(element[0]); return { pre: function pre(scope, element, attrs) { // TODO: Remove this dirty fix! if (element[0].nodeName === 'ons-toolbar') { CustomElements.upgrade(element[0]); GenericView.register(scope, element, attrs, { viewKey: 'ons-toolbar' }); element[0]._ensureNodePosition(); } }, post: function post(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /** * @element ons-toolbar-button */ /** * @attribute var * @initonly * @type {String} * @description * [en]Variable name to refer this button.[/en] * [ja]このボタンを参照するための名前を指定します。[/ja] */ (function () { 'use strict'; var module = angular.module('onsen'); module.directive('onsToolbarButton', ['$onsen', 'GenericView', function ($onsen, GenericView) { return { restrict: 'E', scope: false, link: { pre: function pre(scope, element, attrs) { CustomElements.upgrade(element[0]); var toolbarButton = new GenericView(scope, element, attrs); element.data('ons-toolbar-button', toolbarButton); $onsen.declareVarAttribute(attrs, toolbarButton); $onsen.addModifierMethodsForCustomElements(toolbarButton, element); $onsen.cleaner.onDestroy(scope, function () { toolbarButton._events = undefined; $onsen.removeModifierMethods(toolbarButton); element.data('ons-toolbar-button', undefined); element = null; $onsen.clearComponent({ scope: scope, attrs: attrs, element: element }); scope = element = attrs = null; }); }, post: function post(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } } }; }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); var ComponentCleaner = { /** * @param {jqLite} element */ decomposeNode: function decomposeNode(element) { var children = element.remove().children(); for (var i = 0; i < children.length; i++) { ComponentCleaner.decomposeNode(angular.element(children[i])); } }, /** * @param {Attributes} attrs */ destroyAttributes: function destroyAttributes(attrs) { attrs.$$element = null; attrs.$$observers = null; }, /** * @param {jqLite} element */ destroyElement: function destroyElement(element) { element.remove(); }, /** * @param {Scope} scope */ destroyScope: function destroyScope(scope) { scope.$$listeners = {}; scope.$$watchers = null; scope = null; }, /** * @param {Scope} scope * @param {Function} fn */ onDestroy: function onDestroy(scope, fn) { var clear = scope.$on('$destroy', function () { clear(); fn.apply(null, arguments); }); } }; module.factory('ComponentCleaner', function () { return ComponentCleaner; }); // override builtin ng-(eventname) directives (function () { var ngEventDirectives = {}; 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' ').forEach(function (name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function ($parse) { return { compile: function compile($element, attr) { var fn = $parse(attr[directiveName]); return function (scope, element, attr) { var listener = function listener(event) { scope.$apply(function () { fn(scope, { $event: event }); }); }; element.on(name, listener); ComponentCleaner.onDestroy(scope, function () { element.off(name, listener); element = null; ComponentCleaner.destroyScope(scope); scope = null; ComponentCleaner.destroyAttributes(attr); attr = null; }); }; } }; }]; function directiveNormalize(name) { return name.replace(/-([a-z])/g, function (matches) { return matches[1].toUpperCase(); }); } }); module.config(['$provide', function ($provide) { var shift = function shift($delegate) { $delegate.shift(); return $delegate; }; Object.keys(ngEventDirectives).forEach(function (directiveName) { $provide.decorator(directiveName + 'Directive', ['$delegate', shift]); }); }]); Object.keys(ngEventDirectives).forEach(function (directiveName) { module.directive(directiveName, ngEventDirectives[directiveName]); }); })(); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; var module = angular.module('onsen'); /** * Internal service class for framework implementation. */ module.factory('$onsen', ['$rootScope', '$window', '$cacheFactory', '$document', '$templateCache', '$http', '$q', '$onsGlobal', 'ComponentCleaner', function ($rootScope, $window, $cacheFactory, $document, $templateCache, $http, $q, $onsGlobal, ComponentCleaner) { var $onsen = createOnsenService(); var ModifierUtil = $onsGlobal._internal.ModifierUtil; return $onsen; function createOnsenService() { return { DIRECTIVE_TEMPLATE_URL: 'templates', cleaner: ComponentCleaner, DeviceBackButtonHandler: $onsGlobal._deviceBackButtonDispatcher, _defaultDeviceBackButtonHandler: $onsGlobal._defaultDeviceBackButtonHandler, /** * @return {Object} */ getDefaultDeviceBackButtonHandler: function getDefaultDeviceBackButtonHandler() { return this._defaultDeviceBackButtonHandler; }, /** * @param {Object} view * @param {Element} element * @param {Array} methodNames * @return {Function} A function that dispose all driving methods. */ deriveMethods: function deriveMethods(view, element, methodNames) { methodNames.forEach(function (methodName) { view[methodName] = function () { return element[methodName].apply(element, arguments); }; }); return function () { methodNames.forEach(function (methodName) { view[methodName] = null; }); view = element = null; }; }, /** * @param {Class} klass * @param {Array} properties */ derivePropertiesFromElement: function derivePropertiesFromElement(klass, properties) { properties.forEach(function (property) { Object.defineProperty(klass.prototype, property, { get: function get() { return this._element[0][property]; }, set: function set(value) { return this._element[0][property] = value; // eslint-disable-line no-return-assign } }); }); }, /** * @param {Object} view * @param {Element} element * @param {Array} eventNames * @param {Function} [map] * @return {Function} A function that clear all event listeners */ deriveEvents: function deriveEvents(view, element, eventNames, map) { map = map || function (detail) { return detail; }; eventNames = [].concat(eventNames); var listeners = []; eventNames.forEach(function (eventName) { var listener = function listener(event) { view.emit(eventName, map(Object.create(event.detail))); }; listeners.push(listener); element.addEventListener(eventName, listener, false); }); return function () { eventNames.forEach(function (eventName, index) { element.removeEventListener(eventName, listeners[index], false); }); view = element = listeners = map = null; }; }, /** * @return {Boolean} */ isEnabledAutoStatusBarFill: function isEnabledAutoStatusBarFill() { return !!$onsGlobal._config.autoStatusBarFill; }, /** * @return {Boolean} */ shouldFillStatusBar: $onsGlobal.shouldFillStatusBar, /** * @param {Function} action */ autoStatusBarFill: $onsGlobal.autoStatusBarFill, /** * @param {Object} params * @param {Scope} [params.scope] * @param {jqLite} [params.element] * @param {Array} [params.elements] * @param {Attributes} [params.attrs] */ clearComponent: function clearComponent(params) { if (params.scope) { ComponentCleaner.destroyScope(params.scope); } if (params.attrs) { ComponentCleaner.destroyAttributes(params.attrs); } if (params.element) { ComponentCleaner.destroyElement(params.element); } if (params.elements) { params.elements.forEach(function (element) { ComponentCleaner.destroyElement(element); }); } }, /** * @param {jqLite} element * @param {String} name */ findElementeObject: function findElementeObject(element, name) { return element.inheritedData(name); }, /** * @param {String} page * @return {Promise} */ getPageHTMLAsync: function getPageHTMLAsync(page) { var cache = $templateCache.get(page); if (cache) { var deferred = $q.defer(); var html = typeof cache === 'string' ? cache : cache[1]; deferred.resolve(this.normalizePageHTML(html)); return deferred.promise; } else { return $http({ url: page, method: 'GET' }).then(function (response) { var html = response.data; return this.normalizePageHTML(html); }.bind(this)); } }, /** * @param {String} html * @return {String} */ normalizePageHTML: function normalizePageHTML(html) { html = ('' + html).trim(); if (!html.match(/^<ons-page/)) { html = '<ons-page _muted>' + html + '</ons-page>'; } return html; }, /** * Create modifier templater function. The modifier templater generate css classes bound modifier name. * * @param {Object} attrs * @param {Array} [modifiers] an array of appendix modifier * @return {Function} */ generateModifierTemplater: function generateModifierTemplater(attrs, modifiers) { var attrModifiers = attrs && typeof attrs.modifier === 'string' ? attrs.modifier.trim().split(/ +/) : []; modifiers = angular.isArray(modifiers) ? attrModifiers.concat(modifiers) : attrModifiers; /** * @return {String} template eg. 'ons-button--*', 'ons-button--*__item' * @return {String} */ return function (template) { return modifiers.map(function (modifier) { return template.replace('*', modifier); }).join(' '); }; }, /** * Add modifier methods to view object for custom elements. * * @param {Object} view object * @param {jqLite} element */ addModifierMethodsForCustomElements: function addModifierMethodsForCustomElements(view, element) { var methods = { hasModifier: function hasModifier(needle) { var tokens = ModifierUtil.split(element.attr('modifier')); needle = typeof needle === 'string' ? needle.trim() : ''; return ModifierUtil.split(needle).some(function (needle) { return tokens.indexOf(needle) != -1; }); }, removeModifier: function removeModifier(needle) { needle = typeof needle === 'string' ? needle.trim() : ''; var modifier = ModifierUtil.split(element.attr('modifier')).filter(function (token) { return token !== needle; }).join(' '); element.attr('modifier', modifier); }, addModifier: function addModifier(modifier) { element.attr('modifier', element.attr('modifier') + ' ' + modifier); }, setModifier: function setModifier(modifier) { element.attr('modifier', modifier); }, toggleModifier: function toggleModifier(modifier) { if (this.hasModifier(modifier)) { this.removeModifier(modifier); } else { this.addModifier(modifier); } } }; for (var method in methods) { if (methods.hasOwnProperty(method)) { view[method] = methods[method]; } } }, /** * Add modifier methods to view object. * * @param {Object} view object * @param {String} template * @param {jqLite} element */ addModifierMethods: function addModifierMethods(view, template, element) { var _tr = function _tr(modifier) { return template.replace('*', modifier); }; var fns = { hasModifier: function hasModifier(modifier) { return element.hasClass(_tr(modifier)); }, removeModifier: function removeModifier(modifier) { element.removeClass(_tr(modifier)); }, addModifier: function addModifier(modifier) { element.addClass(_tr(modifier)); }, setModifier: function setModifier(modifier) { var classes = element.attr('class').split(/\s+/), patt = template.replace('*', '.'); for (var i = 0; i < classes.length; i++) { var cls = classes[i]; if (cls.match(patt)) { element.removeClass(cls); } } element.addClass(_tr(modifier)); }, toggleModifier: function toggleModifier(modifier) { var cls = _tr(modifier); if (element.hasClass(cls)) { element.removeClass(cls); } else { element.addClass(cls); } } }; var append = function append(oldFn, newFn) { if (typeof oldFn !== 'undefined') { return function () { return oldFn.apply(null, arguments) || newFn.apply(null, arguments); }; } else { return newFn; } }; view.hasModifier = append(view.hasModifier, fns.hasModifier); view.removeModifier = append(view.removeModifier, fns.removeModifier); view.addModifier = append(view.addModifier, fns.addModifier); view.setModifier = append(view.setModifier, fns.setModifier); view.toggleModifier = append(view.toggleModifier, fns.toggleModifier); }, /** * Remove modifier methods. * * @param {Object} view object */ removeModifierMethods: function removeModifierMethods(view) { view.hasModifier = view.removeModifier = view.addModifier = view.setModifier = view.toggleModifier = undefined; }, /** * Define a variable to JavaScript global scope and AngularJS scope as 'var' attribute name. * * @param {Object} attrs * @param object */ declareVarAttribute: function declareVarAttribute(attrs, object) { if (typeof attrs.var === 'string') { var varName = attrs.var; this._defineVar(varName, object); } }, _registerEventHandler: function _registerEventHandler(component, eventName) { var capitalizedEventName = eventName.charAt(0).toUpperCase() + eventName.slice(1); component.on(eventName, function (event) { $onsen.fireComponentEvent(component._element[0], eventName, event); var handler = component._attrs['ons' + capitalizedEventName]; if (handler) { component._scope.$eval(handler, { $event: event }); component._scope.$evalAsync(); } }); }, /** * Register event handlers for attributes. * * @param {Object} component * @param {String} eventNames */ registerEventHandlers: function registerEventHandlers(component, eventNames) { eventNames = eventNames.trim().split(/\s+/); for (var i = 0, l = eventNames.length; i < l; i++) { var eventName = eventNames[i]; this._registerEventHandler(component, eventName); } }, /** * @return {Boolean} */ isAndroid: function isAndroid() { return !!window.navigator.userAgent.match(/android/i); }, /** * @return {Boolean} */ isIOS: function isIOS() { return !!window.navigator.userAgent.match(/(ipad|iphone|ipod touch)/i); }, /** * @return {Boolean} */ isWebView: function isWebView() { return window.ons.isWebView(); }, /** * @return {Boolean} */ isIOS7above: function () { var ua = window.navigator.userAgent; var match = ua.match(/(iPad|iPhone|iPod touch);.*CPU.*OS (\d+)_(\d+)/i); var result = match ? parseFloat(match[2] + '.' + match[3]) >= 7 : false; return function () { return result; }; }(), /** * Fire a named event for a component. The view object, if it exists, is attached to event.component. * * @param {HTMLElement} [dom] * @param {String} event name */ fireComponentEvent: function fireComponentEvent(dom, eventName, data) { data = data || {}; var event = document.createEvent('HTMLEvents'); for (var key in data) { if (data.hasOwnProperty(key)) { event[key] = data[key]; } } event.component = dom ? angular.element(dom).data(dom.nodeName.toLowerCase()) || null : null; event.initEvent(dom.nodeName.toLowerCase() + ':' + eventName, true, true); dom.dispatchEvent(event); }, /** * Define a variable to JavaScript global scope and AngularJS scope. * * Util.defineVar('foo', 'foo-value'); * // => window.foo and $scope.foo is now 'foo-value' * * Util.defineVar('foo.bar', 'foo-bar-value'); * // => window.foo.bar and $scope.foo.bar is now 'foo-bar-value' * * @param {String} name * @param object */ _defineVar: function _defineVar(name, object) { var names = name.split(/\./); function set(container, names, object) { var name; for (var i = 0; i < names.length - 1; i++) { name = names[i]; if (container[name] === undefined || container[name] === null) { container[name] = {}; } container = container[name]; } container[names[names.length - 1]] = object; if (container[names[names.length - 1]] !== object) { throw new Error('Cannot set var="' + object._attrs.var + '" because it will overwrite a read-only variable.'); } } if (ons.componentBase) { set(ons.componentBase, names, object); } // Attach to ancestor with ons-scope attribute. var element = object._element[0]; while (element.parentNode) { if (element.hasAttribute('ons-scope')) { set(angular.element(element).data('_scope'), names, object); element = null; return; } element = element.parentNode; } element = null; // If no ons-scope element was found, attach to $rootScope. set($rootScope, names, object); } }; } }]); })(); var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION 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. */ ons.notification.alert = function (message) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; typeof message === 'string' ? options.message = message : options = message; var originalCompile = options.compile || function (element) { return element; }; options.compile = function (element) { ons.compile(originalCompile(element)); }; return ons.notification._alertOriginal(options); }; ons.notification.confirm = function (message) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; typeof message === 'string' ? options.message = message : options = message; var originalCompile = options.compile || function (element) { return element; }; options.compile = function (element) { ons.compile(originalCompile(element)); }; return ons.notification._confirmOriginal(options); }; ons.notification.prompt = function (message) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; typeof message === 'string' ? options.message = message : options = message; var originalCompile = options.compile || function (element) { return element; }; options.compile = function (element) { ons.compile(originalCompile(element)); }; return ons.notification._promptOriginal(options); }; var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; // confirm to use jqLite if (window.jQuery && angular.element === window.jQuery) { console.warn('Onsen UI require jqLite. Load jQuery after loading AngularJS to fix this error. jQuery may break Onsen UI behavior.'); // eslint-disable-line no-console } var babelHelpers = {}; babelHelpers.classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; babelHelpers.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; }; }(); babelHelpers.get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; babelHelpers.inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; babelHelpers.possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; babelHelpers; /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { 'use strict'; angular.module('onsen').run(['$templateCache', function ($templateCache) { var templates = window.document.querySelectorAll('script[type="text/ons-template"]'); for (var i = 0; i < templates.length; i++) { var template = angular.element(templates[i]); var id = template.attr('id'); if (typeof id === 'string') { $templateCache.put(id, template.text()); } } }]); })(); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImNsYXNzLmpzIiwidGVtcGxhdGVzLmpzIiwib25zZW4uanMiLCJhbGVydERpYWxvZy5qcyIsImFsZXJ0RGlhbG9nQW5pbWF0b3IuanMiLCJhbmltYXRpb25DaG9vc2VyLmpzIiwiY2Fyb3VzZWwuanMiLCJkaWFsb2cuanMiLCJkaWFsb2dBbmltYXRvci5qcyIsImdlbmVyaWMuanMiLCJsYXp5UmVwZWF0LmpzIiwibGF6eVJlcGVhdERlbGVnYXRlLmpzIiwibW9kYWwuanMiLCJuYXZpZ2F0b3IuanMiLCJuYXZpZ2F0b3JUcmFuc2l0aW9uQW5pbWF0b3IuanMiLCJvdmVybGF5U2xpZGluZ01lbnVBbmltYXRvci5qcyIsInBhZ2UuanMiLCJwb3BvdmVyLmpzIiwicG9wb3ZlckFuaW1hdG9yLmpzIiwicHVsbEhvb2suanMiLCJwdXNoU2xpZGluZ01lbnVBbmltYXRvci5qcyIsInJldmVhbFNsaWRpbmdNZW51QW5pbWF0b3IuanMiLCJzbGlkaW5nTWVudS5qcyIsInNsaWRpbmdNZW51QW5pbWF0b3IuanMiLCJzcGxpdFZpZXcuanMiLCJzcGxpdHRlci1jb250ZW50LmpzIiwic3BsaXR0ZXItc2lkZS5qcyIsInNwbGl0dGVyLmpzIiwic3dpdGNoLmpzIiwidGFiYmFyVmlldy5qcyIsImJh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w7XG4gICAgICAgICAgfTtcbiAgICAgICAgfSxcblxuICAgICAgICAvKipcbiAgICAgICAgICogQHBhcmFtIHtDbGFzc30ga2xhc3NcbiAgICAgICAgICogQHBhcmFtIHtBcnJheX0gcHJvcGVydGllc1xuICAgICAgICAgKi9cbiAgICAgICAgZGVyaXZlUHJvcGVydGllc0Zyb21FbGVtZW50OiBmdW5jdGlvbihrbGFzcywgcHJvcGVydGllcykge1xuICAgICAgICAgIHByb3BlcnRpZXMuZm9yRWFjaChmdW5jdGlvbihwcm9wZXJ0eSkge1xuICAgICAgICAgICAgT2JqZWN0LmRlZmluZVByb3BlcnR5KGtsYXNzLnByb3RvdHlwZSwgcHJvcGVydHksIHtcbiAgICAgICAgICAgICAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIHRoaXMuX2VsZW1lbnRbMF1bcHJvcGVydHldO1xuICAgICAgICAgICAgICB9LFxuICAgICAgICAgICAgICBzZXQ6IGZ1bmN0aW9uKHZhbHVlKSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIHRoaXMuX2VsZW1lbnRbMF1bcHJvcGVydHldID0gdmFsdWU7IC8vIGVzbGludC1kaXNhYmxlLWxpbmUgbm8tcmV0dXJuLWFzc2lnblxuICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9KTtcbiAgICAgICAgICB9KTtcbiAgICAgICAgfSxcblxuICAgICAgICAvKipcbiAgICAgICAgICogQHBhcmFtIHtPYmplY3R9IHZpZXdcbiAgICAgICAgICogQHBhcmFtIHtFbGVtZW50fSBlbGVtZW50XG4gICAgICAgICAqIEBwYXJhbSB7QXJyYXl9IGV2ZW50TmFtZXNcbiAgICAgICAgICogQHBhcmFtIHtGdW5jdGlvbn0gW21hcF1cbiAgICAgICAgICogQHJldHVybiB7RnVuY3Rpb259IEEgZnVuY3Rpb24gdGhhdCBjbGVhciBhbGwgZXZlbnQgbGlzdGVuZXJzXG4gICAgICAgICAqL1xuICAgICAgICBkZXJpdmVFdmVudHM6IGZ1bmN0aW9uKHZpZXcsIGVsZW1lbnQsIGV2ZW50TmFtZXMsIG1hcCkge1xuICAgICAgICAgIG1hcCA9IG1hcCB8fCBmdW5jdGlvbihkZXRhaWwpIHsgcmV0dXJuIGRldGFpbDsgfTtcbiAgICAgICAgICBldmVudE5hbWVzID0gW10uY29uY2F0KGV2ZW50TmFtZXMpO1xuICAgICAgICAgIHZhciBsaXN0ZW5lcnMgPSBbXTtcblxuICAgICAgICAgIGV2ZW50TmFtZXMuZm9yRWFjaChmdW5jdGlvbihldmVudE5hbWUpIHtcbiAgICAgICAgICAgIHZhciBsaXN0ZW5lciA9IGZ1bmN0aW9uKGV2ZW50KSB7XG4gICAgICAgICAgICAgIHZpZXcuZW1pdChldmVudE5hbWUsIG1hcChPYmplY3QuY3JlYXRlKGV2ZW50LmRldGFpbCkpKTtcbiAgICAgICAgICAgIH07XG4gICAgICAgICAgICBsaXN0ZW5lcnMucHVzaChsaXN0ZW5lcik7XG4gICAgICAgICAgICBlbGVtZW50LmFkZEV2ZW50TGlzdGVuZXIoZXZlbnROYW1lLCBsaXN0ZW5lciwgZmFsc2UpO1xuICAgICAgICAgIH0pO1xuXG4gICAgICAgICAgcmV0dXJuIGZ1bmN0aW9uKCkge1xuICAgICAgICAgICAgZXZlbnROYW1lcy5mb3JFYWNoKGZ1bmN0aW9uKGV2ZW50TmFtZSwgaW5kZXgpIHtcbiAgICAgICAgICAgICAgZWxlbWVudC5yZW1vdmVFdmVudExpc3RlbmVyKGV2ZW50TmFtZSwgbGlzdGVuZXJzW2luZGV4XSwgZmFsc2UpO1xuICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICB2aWV3ID0gZWxlbWVudCA9IGxpc3RlbmVycyA9IG1hcCA9IG51bGw7XG4gICAgICAgICAgfTtcbiAgICAgICAgfSxcblxuICAgICAgICAvKipcbiAgICAgICAgICogQHJldHVybiB7Qm9vbGVhbn1cbiAgICAgICAgICovXG4gICAgICAgIGlzRW5hYmxlZEF1dG9TdGF0dXNCYXJGaWxsOiBmdW5jdGlvbigpIHtcbiAgICAgICAgICByZXR1cm4gISEkb25zR2xvYmFsLl9jb25maWcuYXV0b1N0YXR1c0JhckZpbGw7XG4gICAgICAgIH0sXG5cbiAgICAgICAgLyoqXG4gICAgICAgICAqIEByZXR1cm4ge0Jvb2xlYW59XG4gICAgICAgICAqL1xuICAgICAgICBzaG91bGRGaWxsU3RhdHVzQmFyOiAkb25zR2xvYmFsLnNob3VsZEZpbGxTdGF0dXNCYXIsXG5cbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBwYXJhbSB7RnVuY3Rpb259IGFjdGlvblxuICAgICAgICAgKi9cbiAgICAgICAgYXV0b1N0YXR1c0JhckZpbGw6ICRvbnNHbG9iYWwuYXV0b1N0YXR1c0JhckZpbGwsXG5cbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBwYXJhbSB7T2JqZWN0fSBwYXJhbXNcbiAgICAgICAgICogQHBhcmFtIHtTY29wZX0gW3BhcmFtcy5zY29wZV1cbiAgICAgICAgICogQHBhcmFtIHtqcUxpdGV9IFtwYXJhbXMuZWxlbWVudF1cbiAgICAgICAgICogQHBhcmFtIHtBcnJheX0gW3BhcmFtcy5lbGVtZW50c11cbiAgICAgICAgICogQHBhcmFtIHtBdHRyaWJ1dGVzfSBbcGFyYW1zLmF0dHJzXVxuICAgICAgICAgKi9cbiAgICAgICAgY2xlYXJDb21wb25lbnQ6IGZ1bmN0aW9uKHBhcmFtcykge1xuICAgICAgICAgIGlmIChwYXJhbXMuc2NvcGUpIHtcbiAgICAgICAgICAgIENvbXBvbmVudENsZWFuZXIuZGVzdHJveVNjb3BlKHBhcmFtcy5zY29wZSk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHBhcmFtcy5hdHRycykge1xuICAgICAgICAgICAgQ29tcG9uZW50Q2xlYW5lci5kZXN0cm95QXR0cmlidXRlcyhwYXJhbXMuYXR0cnMpO1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGlmIChwYXJhbXMuZWxlbWVudCkge1xuICAgICAgICAgICAgQ29tcG9uZW50Q2xlYW5lci5kZXN0cm95RWxlbWVudChwYXJhbXMuZWxlbWVudCk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHBhcmFtcy5lbGVtZW50cykge1xuICAgICAgICAgICAgcGFyYW1zLmVsZW1lbnRzLmZvckVhY2goZnVuY3Rpb24oZWxlbWVudCkge1xuICAgICAgICAgICAgICBDb21wb25lbnRDbGVhbmVyLmRlc3Ryb3lFbGVtZW50KGVsZW1lbnQpO1xuICAgICAgICAgICAgfSk7XG4gICAgICAgICAgfVxuICAgICAgICB9LFxuXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAcGFyYW0ge2pxTGl0ZX0gZWxlbWVudFxuICAgICAgICAgKiBAcGFyYW0ge1N0cmluZ30gbmFtZVxuICAgICAgICAgKi9cbiAgICAgICAgZmluZEVsZW1lbnRlT2JqZWN0OiBmdW5jdGlvbihlbGVtZW50LCBuYW1lKSB7XG4gICAgICAgICAgcmV0dXJuIGVsZW1lbnQuaW5oZXJpdGVkRGF0YShuYW1lKTtcbiAgICAgICAgfSxcblxuICAgICAgICAvKipcbiAgICAgICAgICogQHBhcmFtIHtTdHJpbmd9IHBhZ2VcbiAgICAgICAgICogQHJldHVybiB7UHJvbWlzZX1cbiAgICAgICAgICovXG4gICAgICAgIGdldFBhZ2VIVE1MQXN5bmM6IGZ1bmN0aW9uKHBhZ2UpIHtcbiAgICAgICAgICB2YXIgY2FjaGUgPSAkdGVtcGxhdGVDYWNoZS5nZXQocGFnZSk7XG5cbiAgICAgICAgICBpZiAoY2FjaGUpIHtcbiAgICAgICAgICAgIHZhciBkZWZlcnJlZCA9ICRxLmRlZmVyKCk7XG5cbiAgICAgICAgICAgIHZhciBodG1sID0gdHlwZW9mIGNhY2hlID09PSAnc3RyaW5nJyA/IGNhY2hlIDogY2FjaGVbMV07XG4gICAgICAgICAgICBkZWZlcn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3IG9iamVjdCBmb3IgY3VzdG9tIGVsZW1lbnRzLlxuICAgICAgICAgKlxuICAgICAgICAgKiBAcGFyYW0ge09iamVjdH0gdmlldyBvYmplY3RcbiAgICAgICAgICogQHBhcmFtIHtqcUxpdGV9IGVsZW1lbnRcbiAgICAgICAgICovXG4gICAgICAgIGFkZE1vZGlmaWVyTWV0aG9kc0ZvckN1c3RvbUVsZW1lbnRzOiBmdW5jdGlvbih2aWV3LCBlbGVtZW50KSB7XG4gICAgICAgICAgdmFyIG1ldGhvZHMgPSB7XG4gICAgICAgICAgICBoYXNNb2RpZmllcjogZnVuY3Rpb24obmVlZGxlKSB7XG4gICAgICAgICAgICAgIHZhciB0b2tlbnMgPSBNb2RpZmllclV0aWwuc3BsaXQoZWxlbWVudC5hdHRyKCdtb2RpZmllcicpKTtcbiAgICAgICAgICAgICAgbmVlZGxlID0gdHlwZW9mIG5lZWRsZSA9PT0gJ3N0cmluZycgPyBuZWVkbGUudHJpbSgpIDogJyc7XG5cbiAgICAgICAgICAgICAgcmV0dXJuIE1vZGlmaWVyVXRpbC5zcGxpdChuZWVkbGUpLnNvbWUoZnVuY3Rpb24obmVlZGxlKSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIHRva2Vucy5pbmRleE9mKG5lZWRsZSkgIT0gLTE7XG4gICAgICAgICAgICAgIH0pO1xuICAgICAgICAgICAgfSxcblxuICAgICAgICAgICAgcmVtb3ZlTW9kaWZpZXI6IGZ1bmN0aW9uKG5lZWRsZSkge1xuICAgICAgICAgICAgICBuZWVkbGUgPSB0eXBlb2YgbmVlZGxlID09PSAnc3RyaW5nJyA/IG5lZWRsZS50cmltKCkgOiAnJztcblxuICAgICAgICAgICAgICB2YXIgbW9kaWZpZXIgPSBNb2RpZmllclV0aWwuc3BsaXQoZWxlbWVudC5hdHRyKCdtb2RpZmllcicpKS5maWx0ZXIoZnVuY3Rpb24odG9rZW4pIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gdG9rZW4gIT09IG5lZWRsZTtcbiAgICAgICAgICAgICAgfSkuam9pbignICcpO1xuXG4gICAgICAgICAgICAgIGVsZW1lbnQuYXR0cignbW9kaWZpZXInLCBtb2RpZmllcik7XG4gICAgICAgICAgICB9LFxuXG4gICAgICAgICAgICBhZGRNb2RpZmllcjogZnVuY3Rpb24obW9kaWZpZXIpIHtcbiAgICAgICAgICAgICAgZWxlbWVudC5hdHRyKCdtb2RpZmllcicsIGVsZW1lbnQuYXR0cignbW9kaWZpZXInKSArICcgJyArIG1vZGlmaWVyKTtcbiAgICAgICAgICAgIH0sXG5cbiAgICAgICAgICAgIHNldE1vZGlmaWVyOiBmdW5jdGlvbihtb2RpZmllcikge1xuICAgICAgICAgICAgICBlbGVtZW50LmF0dHIoJ21vZGlmaWVyJywgbW9kaWZpZXIpO1xuICAgICAgICAgICAgfSxcblxuICAgICAgICAgICAgdG9nZ2xlTW9kaWZpZXI6IGZ1bmN0aW9uKG1vZGlmaWVyKSB7XG4gICAgICAgICAgICAgIGlmICh0aGlzLmhhc01vZGlmaWVyKG1vZGlmaWVyKSkge1xuICAgICAgICAgICAgICAgIHRoaXMucmVtb3ZlTW9kaWZpZXIobW9kaWZpZXIpO1xuICAgICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICAgIHRoaXMuYWRkTW9kaWZpZXIobW9kaWZpZXIpO1xuICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfTtcblxuICAgICAgICAgIGZvciAodmFyIG1ldGhvZCBpbiBtZXRob2RzKSB7XG4gICAgICAgICAgICBpZiAobWV0aG9kcy5oYXNPd25Qcm9wZXJ0eShtZXRob2QpKSB7XG4gICAgICAgICAgICAgIHZpZXdbbWV0aG9kXSA9IG1ldGhvZHNbbWV0aG9kXTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICB9XG4gICAgICAgIH0sXG5cbiAgICAgICAgLyoqXG4gICAgICAgICAqIEFkZCBtb2RpZmllciBtZXRob2RzIHRvIHZpZXcgb2JqZWN0LlxuICAgICAgICAgKlxuICAgICAgICAgKiBAcGFyYW0ge09iamVjdH0gdmlldyBvYmplY3RcbiAgICAgICAgICogQHBhcmFtIHtTdHJpbmd9IHRlbXBsYXRlXG4gICAgICAgICAqIEBwYXJhbSB7anFMaXRlfSBlbGVtZW50XG4gICAgICAgICAqL1xuICAgICAgICBhZGRNb2RpZmllck1ldGhvZHM6IGZ1bmN0aW9uKHZpZXcsIHRlbXBsYXRlLCBlbGVtZW50KSB7XG4gICAgICAgICAgdmFyIF90ciA9IGZ1bmN0aW9uKG1vZGlmaWVyKSB7XG4gICAgICAgICAgICByZXR1cm4gdGVtcGxhdGUucmVwbGFjZSgnKicsIG1vZGlmaWVyKTtcbiAgICAgICAgICB9O1xuXG4gICAgICAgICAgdmFyIGZucyA9IHtcbiAgICAgICAgICAgIGhhc01vZGlmaWVyOiBmdW5jdGlvbihtb2RpZmllcikge1xuICAgICAgICAgICAgICByZXR1cm4gZWxlbWVudC5oYXNDbGFzcyhfdHIobW9kaWZpZXIpKTtcbiAgICAgICAgICAgIH0sXG5cbiAgICAgICAgICAgIHJlbW92ZU1vZGlmaWVyOiBmdW5jdGlvbihtb2RpZmllcikge1xuICAgICAgICAgICAgICBlbGVtZW50LnJlbW92ZUNsYXNzKF90cihtb2RpZmllcikpO1xuICAgICAgICAgICAgfSxcblxuICAgICAgICAgICAgYWRkTW9kaWZpZXI6IGZ1bmN0aW9uKG1vZGlmaWVyKSB7XG4gICAgICAgICAgICAgIGVsZW1lbnQuYWRkQ2xhc3MoX3RyKG1vZGlmaWVyKSk7XG4gICAgICAgICAgICB9LFxuXG4gICAgICAgICAgICBzZXRNb2RpZmllcjogZnVuY3Rpb24obW9kaWZpZXIpIHtcbiAgICAgICAgICAgICAgdmFyIGNsYXNzZXMgPSBlbGVtZW50LmF0dHIoJ2NsYXNzJykuc3BsaXQoL1xccysvKSxcbiAgICAgICAgICAgICAgICAgIHBhdHQgPSB0ZW1wbGF0ZS5yZXBsYWNlKCcqJywgJy4nKTtcblxuICAgICAgICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IGNsYXNzZXMubGVuZ3RoOyBpKyspIHtcbiAgICAgICAgICAgICAgICB2YXIgY2xzID0gY2xhc3Nlc1tpXTtcblxuICAgICAgICAgICAgICAgIGlmIChjbHMubWF0Y2gocGF0dCkpIHtcbiAgICAgICAgICAgICAgICAgIGVsZW1lbnQucmVtb3ZlQ2xhc3MoY2xzKTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgIH1cblxuICAgICAgICAgICAgICBlbGVtZW50LmFkZENsYXNzKF90cihtb2RpZmllcikpO1xuICAgICAgICAgICAgfSxcblxuICAgICAgICAgICAgdG9nZ2xlTW9kaWZpZXI6IGZ1bmN0aW9uKG1vZGlmaWVyKSB7XG4gICAgICAgICAgICAgIHZhciBjbHMgPSBfdHIobW9kaWZpZXIpO1xuICAgICAgICAgICAgICBpZiAoZWxlbWVudC5oYXNDbGFzcyhjbHMpKSB7XG4gICAgICAgICAgICAgICAgZWxlbWVudC5yZW1vdmVDbGFzcyhjbHMpO1xuICAgICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICAgIGVsZW1lbnQuYWRkQ2xhc3MoY2xzKTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfVxuICAgICAgICAgIH07XG5cbiAgICAgICAgICB2YXIgYXBwZW5kID0gZnVuY3Rpb24ob2xkRm4sIG5ld0ZuKSB7XG4gICAgICAgICAgICBpZiAodHlwZW9mIG9sZEZuICE9PSAndW5kZWZpbmVkJykge1xuICAgICAgICAgICAgICByZXR1cm4gZnVuY3Rpb24oKSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIG9sZEZuLmFwcGx5KG51bGwsIGFyZ3VtZW50cykgfHwgbmV3Rm4uYXBwbHkobnVsbCwgYXJndW1lbnRzKTtcbiAgICAgICAgICAgICAgfTtcbiAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgIH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IEFuZ3VsYXJKUyBzY29wZSBhcyAndmFyJyBhdHRyaWJ1dGUgbmFtZS5cbiAgICAgICAgICpcbiAgICAgICAgICogQHBhcmFtIHtPYmplY3R9IGF0dHJzXG4gICAgICAgICAqIEBwYXJhbSBvYmplY3RcbiAgICAgICAgICovXG4gICAgICAgIGRlY2xhcmVWYXJBdHRyaWJ1dGU6IGZ1bmN0aW9uKGF0dHJzLCBvYmplY3QpIHtcbiAgICAgICAgICBpZiAodHlwZW9mIGF0dHJzLnZhciA9PT0gJ3N0cmluZycpIHtcbiAgICAgICAgICAgIHZhciB2YXJOYW1lID0gYXR0cnMudmFyO1xuICAgICAgICAgICAgdGhpcy5fZGVmaW5lVmFyKHZhck5hbWUsIG9iamVjdCk7XG4gICAgICAgICAgfVxuICAgICAgICB9LFxuXG4gICAgICAgIF9yZWdpc3RlckV2ZW50SGFuZGxlcjogZnVuY3Rpb24oY29tcG9uZW50LCBldmVudE5hbWUpIHtcbiAgICAgICAgICB2YXIgY2FwaXRhbGl6ZWRFdmVudE5hbWUgPSBldmVudE5hbWUuY2hhckF0KDApLnRvVXBwZXJDYXNlKCkgKyBldmVudE5hbWUuc2xpY2UoMSk7XG5cbiAgICAgICAgICBjb21wb25lbnQub24oZXZlbnROYW1lLCBmdW5jdGlvbihldmVudCkge1xuICAgICAgICAgICAgJG9uc2VuLmZpcmVDb21wb25lbnRFdmVudChjb21wb25lbnQuX2VsZW1lbnRbMF0sIGV2ZW50TmFtZSwgZXZlbnQpO1xuXG4gICAgICAgICAgICB2YXIgaGFuZGxlciA9IGNvbXBvbmVudC5fYXR0cnNbJ29ucycgKyBjYXBpdGFsaXplZEV2ZW50TmFtZV07XG4gICAgICAgICAgICBpZiAoaGFuZGxlcikge1xuICAgICAgICAgICAgICBjb21wb25lbnQuX3Njb3BlLiRldmFsKGhhbmRsZXIsIHskZXZlbnQ6IGV2ZW50fSk7XG4gICAgICAgICAgICAgIGNvbXBvbmVudC5fc2NvcGUuJGV2YWxBc3luYygpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgIH0pO1xuICAgICAgICB9LFxuXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBSZWdpc3RlciBldmVudCBoYW5kbGVycyBmb3IgYXR0cmlidXRlcy5cbiAgICAgICAgICpcbiAgICAgICAgICogQHBhcmFtIHtPYmplY3R9IGNvbXBvbmVudFxuICAgICAgICAgKiBAcGFyYW0ge1N0cmluZ30gZXZlbnROYW1lc1xuICAgICAgICAgKi9cbiAgICAgICAgcmVnaXN0ZXJFdmVudEhhbmRsZXJzOiBmdW5jdGlvbihjb21wb25lbnQsIGV2ZW50TmFtZXMpIHtcbiAgICAgICAgICBldmVudE5hbWVzID0gZXZlbnROYW1lcy50cmltKCkuc3BsaXQoL1xccysvKTtcblxuICAgICAgICAgIGZvciAodmFyIGkgPSAwLCBsID0gZXZlbnROYW1lcy5sZW5ndGg7IGkgPCBsOyBpKyspIHtcbiAgICAgICAgICAgIHZhciBldmVudE5hbWUgPSBldmVudE5hbWVzW2ldO1xuICAgICAgICAgICAgdGhpcy5fcmVnaXN0ZXJFdmVudEhhbmRsZXIoY29tcG9uZW50LCBldmVudE5hbWUpO1xuICAgICAgICAgIH1cbiAgICAgICAgfSxcblxuICAgICAgICAvKipcbiAgICAgICAgICogQHJldHVybiB7Qm9vbGVhbn1cbiAgICAgICAgICovXG4gICAgICAgIGlzQW5kcm9pZDogZnVuY3Rpb24oKSB7XG4gICAgICAgICAgcmV0dXJuICEhd2luZG93Lm5hdmlnYXRvci51c2VyQWdlbnQubWF0Y2goL2FuZHJvaWQvaSk7XG4gICAgICAgIH0sXG5cbiAgICAgICAgLyoqXG4gICAgICAgICAqIEByZXR1cm4ge0Jvb2xlYW59XG4gICAgICAgICAqL1xuICAgICAgICBpc0lPUzogZnVuY3Rpb24oKSB7XG4gICAgICAgICAgcmV0dXJuICEhd2luZG93Lm5hdmlnYXRvci51c2VyQWdlbnQubWF0Y2goLyhpcGFkfGlwaG9uZXxpcG9kIHRvdWNoKS9pKTtcbiAgICAgICAgfSxcblxuICAgICAgICAvKipcbiAgICAgICAgICogQHJldHVybiB7Qm9vbGVhbn1cbiAgICAgICAgICovXG4gICAgICAgIGlzV2ViVmlldzogZnVuY3Rpb24oKSB7XG4gICAgICAgICAgcmV0dXJuIHdpbmRvdy5vbnMuaXNXZWJWaWV3KCk7XG4gICAgICAgIH0sXG5cbiAgICAgICAgLyoqXG4gICAgICAgICAqIEByZXR1cm4ge0Jvb2xlYW59XG4gICAgICAgICAqL1xuICAgICAgICBpc0lPUzdhYm92ZTogKGZ1bmN0aW9uKCkge1xuICAgICAgICAgIHZhciB1YSA9IHdpbmRvdy5uYXZpZ2F0b3IudXNlckFnZW50O1xuICAgICAgICAgIHZhciBtYXRjaCA9IHVhLm1hdGNoKC8oaVBhZHxpUGhvbmV8aVBvZCB0b3VjaCk7LipDUFUuKk9TIChcXGQrKV8oXFxkKykvaSk7XG5cbiAgICAgICAgICB2YXIgcmVzdWx0ID0gbWF0Y2ggPyBwYXJzZUZsb2F0KG1hdGNoWzJdICsgJy4nICsgbWF0Y2hbM10pID49IDcgOiBmYWxzZTtcblxuICAgICAgICAgIHJldHVybiBmdW5jdGlvbigpIHtcbiAgICAgICAgICAgIHJldHVybiByZXN1bHQ7XG4gICAgICAgICAgfTtcbiAgICAgICAgfSkoKSxcblxuICAgICAgICAvKipcbiAgICAgICAgICogRmlyZSBhIG5hbWVkIGV2ZW50IGZvciBhIGNvbXBvbmVudC4gVGhlIHZpZXcgb2JqZWN0LCBpZiBpdCBleGlzdHMsIGlzIGF0dGFjaGVkIHRvIGV2ZW50LmNvbXBvbmVudC5cbiAgICAgICAgICpcbiAgICAgICAgICogQHBhcmFtIHtIVE1MRWxlbWVudH0gW2RvbV1cbiAgICAgICAgICogQHBhcmFtIHtTdHJpbmd9IGV2ZW50IG5hbWVcbiAgICAgICAgICovXG4gICAgICAgIGZpcmVDb21wb25lbnRFdmVudDogZnVuY3Rpb24oZG9tLCBldmVudE5hbWUsIGRhdGEpIHtcbiAgICAgICAgICBkYXRhID0gZGF0YSB8fCB7fTtcblxuICAgICAgICAgIHZhciBldmVudCA9IGRvY3VtZW50LmNyZWF0ZUV2ZW50KCdIVE1MRXZlbnRzJyk7XG5cbiAgICAgICAgICBmb3IgKHZhciBrZXkgaW4gZGF0YSkge1xuICAgICAgICAgICAgaWYgKGRhdGEuaGFzT3duUHJvcGVydHkoa2V5KSkge1xuICAgICAgICAgICAgICBldmVudFtrZXldID0gZGF0YVtrZXldO1xuICAgICAgICAgICAgfVxuICAgICAgICAgIH1cblxuICAgICAgICAgIGV2ZW50LmNvbXBvbmVudCA9IGRvbSA/XG4gICAgICAgICAgICBhbmd1bGFyLmVsZW1lbnQoZG9tKS5kYXRhKGRvbS5ub2RlTmFtZS50b0xvd2VyQ2FzZSgpKSB8fCBudWxsIDogbnVsbDtcbiAgICAgICAgICBldmVudC5pbml0RXZlbnQoZG9tLm5vZGVOYW1lLnRvTG93ZXJDYXNlKCkgKyAnOicgKyBldmVudE5hbWUsIHRydWUsIHRydWUpO1xuXG4gICAgICAgICAgZG9tLmRpc3BhdGNoRXZlbnQoZXZlbnQpO1xuICAgICAgICB9LFxuXG4gICAgICAgIC8qKlxuICAgICAgICAgKiBEZWZpbmUgYSB2YXJpYWJsZSB0byBKYXZhU2NyaXB0IGdsb2JhbCBzY29wZSBhbmQgQW5ndWxhckpTIHNjb3BlLlxuICAgICAgICAgKlxuICAgICAgICAgKiBVdGlsLmRlZmluZVZhcignZm9vJywgJ2Zvby12YWx1ZScpO1xuICAgICAgICAgKiAvLyA9PiB3aW5kb3cuZm9vIGFuZCAkc2NvcGUuZm9vIGlzIG5vdyAnZm9vLXZhbHVlJ1xuICAgICAgICAgKlxuICAgICAgICAgKiBVdGlsLmRlZmluZVZhcignZm9vLmJhcicsICdmb28tYmFyLXZhbHVlJyk7XG4gICAgICAgICAqIC8vID0+IHdpbmRvdy5mb28uYmFyIGFuZCAkc2NvcGUuZm9vLmJhciBpcyBub3cgJ2Zvby1iYXItdmFsdWUnXG4gICAgICAgICAqXG4gICAgICAgICAqIEBwYXJhbSB7U3RyaW5nfSBuYW1lXG4gICAgICAgICAqIEBwYXJhbSBvYmplY3RcbiAgICAgICAgICovXG4gICAgICAgIF9kZWZpbmVWYXI6IGZ1bmN0aW9uKG5hbWUsIG9iamVjdCkge1xuICAgICAgICAgIHZhciBuYW1lcyA9IG5hbWUuc3BsaXQoL1xcLi8pO1xuXG4gICAgICAgICAgZnVuY3Rpb24gc2V0KGNvbnRhaW5lciwgbmFtZXMsIG9iamVjdCkge1xuICAgICAgICAgICAgdmFyIG5hbWU7XG4gICAgICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IG5hbWVzLmxlbmd0aCAtIDE7IGkrKykge1xuICAgICAgICAgICAgICBuYW1lID0gbmFtZXNbaV07XG4gICAgICAgICAgICAgIGlmIChjb250YWluZXJbbmFtZV0gPT09IHVuZGVmaW5lZCB8fCBjb250YWluZXJbbmFtZV0gPT09IG51bGwpIHtcbiAgICAgICAgICAgICAgICBjb250YWluZXJbbmFtZV0gPSB7fTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICBjb250YWluZXIgPSBjb250YWluZXJbbmFtZV07XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIGNvbnRhaW5lcltuYW1lc1tuYW1lcy5sZW5ndGggLSAxXV0gPSBvYmplY3Q7XG5cbiAgICAgICAgICAgIGlmIChjb250YWluZXJbbmFtZXNbbmFtZXMubGVuZ3RoIC0gMV1dICE9PSBvYmplY3QpIHtcbiAgICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdDYW5ub3Qgc2V0IHZhcj1cIicgKyBvYmplY3QuX2F0dHJzLnZhciArICdcIiBiZWNhdXNlIGl0IHdpbGwgb3ZlcndyaXRlIGEgcmVhZC1vbmx5IHZhcmlhYmxlLicpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgIH1cblxuICAgICAgICAgIGlmIChvbnMuY29tcG9u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R0cnM7XG5cbiAgICAgICAgaWYgKG9wdGlvbnMuZGlyZWN0aXZlT25seSkge1xuICAgICAgICAgIGlmICghb3B0aW9ucy5tb2RpZmllclRlbXBsYXRlKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ29wdGlvbnMubW9kaWZpZXJUZW1wbGF0ZSBpcyB1bmRlZmluZWQuJyk7XG4gICAgICAgICAgfVxuICAgICAgICAgICRvbnNlbi5hZGRNb2RpZmllck1ldGhvZHModGhpcywgb3B0aW9ucy5tb2RpZmllclRlbXBsYXRlLCBlbGVtZW50KTtcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAkb25zZW4uYWRkTW9kaWZpZXJNZXRob2RzRm9yQ3VzdG9tRWxlbWVudHModGhpcywgZWxlbWVudCk7XG4gICAgICAgIH1cblxuICAgICAgICAkb25zZW4uY2xlYW5lci5vbkRlc3Ryb3koc2NvcGUsIGZ1bmN0aW9uKCkge1xuICAgICAgICAgIHNlbGYuX2V2ZW50cyA9IHVuZGVmaW5lZDtcbiAgICAgICAgICAkb25zZW4ucmVtb3ZlTW9kaWZpZXJNZXRob2RzKHNlbGYpO1xuXG4gICAgICAgICAgaWYgKG9wdGlvbnMub25EZXN0cm95KSB7XG4gICAgICAgICAgICBvcHRpb25zLm9uRGVzdHJveShzZWxmKTtcbiAgICAgICAgICB9XG5cbiAgICAgICAgICAkb25zZW4uY2xlYXJDb21wb25lbnQoe1xuICAgICAgICAgICAgc2NvcGU6IHNjb3BlLFxuICAgICAgICAgICAgYXR0cnM6IGF0dHJzLFxuICAgICAgICAgICAgZWxlbWVudDogZWxlbWVudFxuICAgICAgICAgIH0pO1xuXG4gICAgICAgICAgc2VsZiA9IGVsZW1lbnQgPSBzZWxmLl9lbGVtZW50ID0gc2VsZi5fc2NvcGUgPSBzY29wZSA9IHNlbGYuX2F0dHJzID0gYXR0cnMgPSBvcHRpb25zID0gbnVsbDtcbiAgICAgICAgfSk7XG4gICAgICB9XG4gICAgf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lbnQ7XG4gICAgICAgIHRoaXMuX21haW5QYWdlID0gbWFpblBhZ2U7XG4gICAgICAgIHRoaXMuX21lbnVQYWdlID0gbWVudVBhZ2U7XG5cbiAgICAgICAgbWVudVBhZ2UuY3NzKCdib3gtc2hhZG93JywgJzBweCAwIDEwcHggMHB4IHJnYmEoMCwgMCwgMCwgMC4yKScpO1xuICAgICAgICBtZW51UGFnZS5jc3Moe1xuICAgICAgICAgIHdpZHRoOiBvcHRpb25zLndpZHRoLFxuICAgICAgICAgIGRpc3BsYXk6ICdub25lJyxcbiAgICAgICAgICB6SW5kZXg6IDJcbiAgICAgICAgfSk7XG5cbiAgICAgICAgLy8gRml4IGZvciB0cmFuc3BhcmVudCBtZW51IHBhZ2Ugb24gaU9TOC5cbiAgICAgICAgbWVudVBhZ2UuY3NzKCctd2Via2l0LXRyYW5zZm9ybScsICd0cmFuc2xhdGUzZCgwcHgsIDBweCwgMHB4KScpO1xuXG4gICAgICAgIG1haW5QYWdlLmNzcyh7ekluZGV4OiAxfSk7XG5cbiAgICAgICAgaWYgKHRoaXMuX2lzUmlnaHQpIHtcbiAgICAgICAgICBtZW51UGFnZS5jc3Moe1xuICAgICAgICAgICAgcmlnaHQ6ICctJyArIG9wdGlvbnMud2lkdGgsXG4gICAgICAgICAgICBsZWZ0OiAnYXV0bydcbiAgICAgICAgICB9KTtcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBtZW51UGFnZS5jc3Moe1xuICAgICAgICAgICAgcmlnaHQ6ICdhdXRvJyxcbiAgICAgICAgICAgIGxlZnQ6ICctJyArIG9wdGlvbnMud2lkdGhcbiAgICAgICAgICB9KTtcbiAgICAgICAgfVxuXG4gICAgICAgIHRoaXMuX2JsYWNrTWFzayA9IGFuZ3VsYXIuZWxlbWVudCgnPGRpdj48L2Rpdj4nKS5jc3Moe1xuICAgICAgICAgIGJhY2tncm91bmRDb2xvcjogJ2JsYWNrJyxcbiAgICAgICAgICB0b3A6ICcwcHgnLFxuICAgIC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RoO1xuICAgICAgICB2YXIgbWVudVN0eWxlID0gdGhpcy5fZ2VuZXJhdGVNZW51UGFnZVN0eWxlKG1heCk7XG4gICAgICAgIHZhciBtYWluUGFnZVN0eWxlID0gdGhpcy5fZ2VuZXJhdGVNYWluUGFnZVN0eWxlKG1heCk7XG5cbiAgICAgICAgc2V0VGltZW91dChmdW5jdGlvbigpIHtcblxuICAgICAgICAgIGFuaW1pdCh0aGlzLl9tYWluUGFnZVswXSlcbiAgICAgICAgICAgIC53YWl0KGRlbGF5KVxuICAgICAgICAgICAgLnF1ZXVlKG1haW5QYWdlU3R5bGUsIHtcbiAgICAgICAgICAgICAgZHVyYXRpb246IGR1cmF0aW9uLFxuICAgICAgICAgICAgICB0aW1pbmc6IHRoaXMudGltaW5nXG4gICAgICAgICAgICB9KVxuICAgICAgICAgICAgLnF1ZXVlKGZ1bmN0aW9uKGRvbmUpIHtcbiAgICAgICAgICAgICAgY2FsbGJhY2soKTtcbiAgICAgICAgICAgICAgZG9uZSgpO1xuICAgICAgICAgICAgfSlcbiAgICAgICAgICAgIC5wbGF5KCk7XG5cbiAgICAgICAgICBhbmltaXQodGhpcy5fbWVudVBhZ2VbMF0pXG4gICAgICAgICAgICAud2FpdChkZWxheSlcbiAgICAgICAgICAgIC5xdWV1ZShtZW51U3R5bGUsIHtcbiAgICAgICAgICAgICAgZHVyYXRpb246IGR1cmF0aW9uLFxuICAgICAgICAgICAgICB0aW1pbmc6IHRoaXMudGltaW5nXG4gICAgICAgICAgICB9KVxuICAgICAgICAgICAgLnBsYXkoKTtcblxuICAgICAgICB9LmJpbmQodGhpcyksIDEwMDAgLyA2MCk7XG4gICAgICB9LFxuXG4gICAgICAvKipcbiAgICAgICAqIEBwYXJhbSB7RnVuY3Rpb259IGNhbGxiYWNrXG4gICAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IGluc3RhbnRcbiAgICAgICAqL1xuICAgICAgY2xvc2VNZW51OiBmdW5jdGlvbihjYWxsYmFjaywgaW5zdGFudCkge1xuICAgICAgICB2YXIgZHVyYXRpb24gPSBpbnN0YW50ID09PSB0cnVlID8gMC4wIDogdGhpcy5kdXJhdGlvbjtcbiAgICAgICAgdmFyIGRlbGF5ID0gaW5zdGFudCA9PT0gdHJ1ZSA/IDAuMCA6IHRoaXMuZGVsYXk7XG5cbiAgICAgICAgdGhpcy5fYmxhY2tNYXNrLmNzcyh7ZGlzcGxheTogJ2Jsb2NrJ30pO1xuXG4gICAgICAgIHZhciBtZW51UGFnZVN0eWxlID0gdGhpcy5fZ2VuZXJhdGVNZW51UGFnZVN0eWxlKDApO1xuICAgICAgICB2YXIgbWFpblBhZ2VTdHlsZSA9IHRoaXMuX2dlbmVyYXRlTWFpblBhZ2VTdHlsZSgwKTtcblxuICAgICAgICBzZXRUaW1lb3V0KGZ1bmN0aW9uKCkge1xuXG4gICAgICAgICAgYW5pbWl0KHRoaXMuX21haW5QYWdlWzBdKVxuICAgICAgICAgICAgLndhaXQoZGVsYXkpXG4gICAgICAgICAgICAucXVldWUobWFpblBhZ2VTdHlsZSwge1xuICAgICAgICAgICAgICBkdXJhdGlvbjogZHVyYXRpb24sXG4gICAgICAgICAgICAgIHRpbWluZzogdGhpcy50aW1pbmdcbiAgICAgICAgICAgIH0pXG4gICAgICAgICAgICAucXVldWUoZnVuY3Rpb24oZG9uZSkge1xuICAgICAgICAgICAgICB0aGlzLl9tZW51UGFnZS5jc3MoJ2Rpc3BsYXknLCAnbm9uZScpO1xuICAgICAgICAgICAgICBjYWxsYmFjaygpO1xuICAgICAgICAgICAgICBkb25lKCk7XG4gICAgICAgICAgICB9LmJpbmQodGhpcykpXG4gICAgICAgICAgICAucGxheSgpO1xuXG4gICAgICAgICAgYW5pbWl0KHRoaXMuX21lbnVQYWdlWzBdKVxuICAgICAgICAgICAgLndhaXQoZGVsYXkpXG4gICAgICAgICAgICAucXVldWUobWVudVBhZ2VTdHlsZSwge1xuICAgICAgICAgICAgICBkdXJhdGlvbjogZHVyYXRpb24sXG4gICAg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Rob2RzRm9yQ3VzdG9tRWxlbWVudHMocGFnZSwgZWxlbWVudCk7XG5cbiAgICAgICAgICAgIGVsZW1lbnQuZGF0YSgnX3Njb3BlJywgc2NvcGUpO1xuXG4gICAgICAgICAgICAkb25zZW4uY2xlYW5lci5vbkRlc3Ryb3koc2NvcGUsIGZ1bmN0aW9uKCkge1xuICAgICAgICAgICAgICBwYWdlLl9ldmVudHMgPSB1bmRlZmluZWQ7XG4gICAgICAgICAgICAgICRvbnNlbi5yZW1vdmVNb2RpZmllck1ldGhvZHMocGFnZSk7XG4gICAgICAgICAgICAgIGVsZW1lbnQuZGF0YSgnb25zLXBhZ2UnLCB1bmRlZmluZWQpO1xuICAgICAgICAgICAgICBlbGVtZW50LmRhdGEoJ19zY29wZScsIHVuZGVmaW5lZCk7XG5cbiAgICAgICAgICAgICAgJG9uc2VuLmNsZWFyQ29tcG9uZW50KHtcbiAgICAgICAgICAgICAgICBlbGVtZW50OiBlbGVtZW50LFxuICAgICAgICAgICAgICAgIHNjb3BlOiBzY29wZSxcbiAgICAgICAgICAgICAgICBhdHRyczogYXR0cnNcbiAgICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICAgIHNjb3BlID0gZWxlbWVudCA9IGF0dHJzID0gbnVsbDtcbiAgICAgICAgICAgIH0pO1xuICAgICAgICAgIH0sXG5cbiAgICAgICAgICBwb3N0OiBmdW5jdGlvbiBwb3N0TGluayhzY29wZSwgZWxlbWVudCwgYXR0cnMpIHtcbiAgICAgICAgICAgIGZpcmVQYWdlSW5pdEV2ZW50KGVsZW1lbnRbMF0pO1xuICAgICAgICAgIH1cbiAgICAgICAgfTtcbiAgICAgIH1cbiAgICB9O1xuICB9KTtcbn0pKCk7XG4iLCIvKipcbiAqIEBlbGVtZW50IG9ucy1wb3BvdmVyXG4gKi9cblxuLyoqXG4gKiBAYXR0cmlidXRlIHZhclxuICogQGluaXRvbmx5XG4gKiBAdHlwZSB7U3RyaW5nfVxuICogQGRlc2NyaXB0aW9uXG4g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udDtcbiAgICAgICAgdGhpcy5fbWFpblBhZ2UgPSBtYWluUGFnZTtcbiAgICAgICAgdGhpcy5fbWVudVBhZ2UgPSBtZW51UGFnZTtcblxuICAgICAgICB0aGlzLl9pc1JpZ2h0ID0gISFvcHRpb25zLmlzUmlnaHQ7XG4gICAgICAgIHRoaXMuX3dpZHRoID0gb3B0aW9ucy53aWR0aCB8fCAnOTAlJztcblxuICAgICAgICBtZW51UGFnZS5jc3Moe1xuICAgICAgICAgIHdpZHRoOiBvcHRpb25zLndpZHRoLFxuICAgICAgICAgIGRpc3BsYXk6ICdub25lJ1xuICAgICAgICB9KTtcblxuICAgICAgICBpZiAodGhpcy5faXNSaWdodCkge1xuICAgICAgICAgIG1lbnVQYWdlLmNzcyh7XG4gICAgICAgICAgICByaWdodDogJy0nICsgb3B0aW9ucy53aWR0aCxcbiAgICAgICAgICAgIGxlZnQ6ICdhdXRvJ1xuICAgICAgICAgIH0pO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIG1lbnVQYWdlLmNzcyh7XG4gICAgICAgICAgICByaWdodDogJ2F1dG8nLFxuICAgICAgICAgICAgbGVmdDogJy0nICsgb3B0aW9ucy53aWR0aFxuICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICB9LFxuXG4gICAgICAvKipcbiAgICAgICAqIEBwYXJhbSB7T2JqZWN0fSBvcHRpb25zXG4gICAgICAgKiBAcGFyYW0ge1N0cmluZ30gb3B0aW9ucy53aWR0aFxuICAgICAgICogQHBhcmFtIHtPYmplY3R9IG9wdGlvbnMuaXNSaWdodFxuICAgICAgICovXG4gICAgICBvblJlc2l6ZWQ6IGZ1bmN0aW9uKG9wdGlvbnMpIHtcbiAgICAgICAgdGhpcy5fbWVudVBhZ2UuY3NzKCd3aWR0aCcsIG9wdGlvbnMud2lkdGgpO1xuXG4gICAgICAgIGlmICh0aGlzLl9pc1JpZ2h0KSB7XG4gICAgICAgICAgdGhpcy5fbWVudVBhZ2UuY3NzKHtcbiA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gICAgICAgICAgIGRvbmUoKTtcbiAgICAgICAgICAgIH0pXG4gICAgICAgICAgICAucGxheSgpO1xuXG4gICAgICAgICAgYW5pbWl0KHRoaXMuX21lbnVQYWdlWzBdKVxuICAgICAgICAgICAgLndhaXQoZGVsYXkpXG4gICAgICAgICAgICAucXVldWUoYmVoaW5kU3R5bGUsIHtcbiAgICAgICAgICAgICAgZHVyYXRpb246IGR1cmF0aW9uLFxuICAgICAgICAgICAgICB0aW1pbmc6IHRoaXMudGltaW5nXG4gICAgICAgICAgICB9KVxuICAgICAgICAgICAgLnBsYXkoKTtcblxuICAgICAgICB9LmJpbmQodGhpcyksIDEwMDAgLyA2MCk7XG4gICAgICB9LFxuXG4gICAgICAvKipcbiAgICAgICAqIEBwYXJhbSB7RnVuY3Rpb259IGNhbGxiYWNrXG4gICAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IGluc3RhbnRcbiAgICAgICAqL1xuICAgICAgY2xvc2VNZW51OiBmdW5jdGlvbihjYWxsYmFjaywgaW5zdGFudCkge1xuICAgICAgICB2YXIgZHVyYXRpb24gPSBpbnN0YW50ID09PSB0cnVlID8gMC4wIDogdGhpcy5kdXJhdGlvbjtcbiAgICAgICAgdmFyIGRlbGF5ID0gaW5zdGFudCA9PT0gdHJ1ZSA/IDAuMCA6IHRoaXMuZGVsYXk7XG5cbiAgICAgICAgdmFyIGFib3ZlVHJhbnNmb3JtID0gdGhpcy5fZ2VuZXJhdGVBYm92ZVBhZ2VUcmFuc2Zvcm0oMCk7XG4gICAgICAgIHZhciBiZWhpbmRTdHlsZSA9IHRoaXMuX2dlbmVyYXRlQmVoaW5kUGFnZVN0eWxlKDApO1xuXG4gICAgICAgIHNldFRpbWVvdXQoZnVuY3Rpb24oKSB7XG5cbiAgICAgICAgICBhbmltaXQodGhpcy5fbWFpblBhZ2VbMF0pXG4gICAgICAgICAgICAud2FpdChkZWxheSlcbiAgICAgICAgICAgIC5xdWV1ZSh7XG4gICAgICAgICAgICAgIHRyYW5zZm9ybTogYWJvdmVUcmFuc2Zvcm1cbiAgICAgICAgICAgIH0sIHtcbiAgICAgICAgICAgICAgZHVyYXRpb246IGR1cmF0aW9uLFxuICAgICAgICAgICAgICB0aW1pbmc6IHRoaXMudGltaW5nXG4gICAgICAgICAgICB9KVxuICAgICAgICAgICAgLnF1ZXVlKHtcbiAgICAgICAgICAgICAgdHJhbnNmb3JtOiAndHJhbnNsYXRlM2QoMCwgMCwgMCknXG4gICAgICAgICAgICB9KVxuICAgICAgICAgICAgLnF1ZXVlKGZ1bmN0aW9uKGRvbmUpIHtcbiAgICAgICAgICAgICAgdGhpcy5fbWVudVBhZ2UuY3NzKCdkaXNwbGF5JywgJ25vbmUnKTtcbiAgICAgICAgICAgICAgY2FsbGJhY2soKTtcbiAgICAgICAgICAgICAgZG9uZSgpO1xuICAgICAgICAgICAgfS5iaW5kKHRoaXMpKVxuICAgICAgICAgICAgLnBsYXkoKTtcblxuICAgICAgICAgIGFuaW1pdCh0aGlzLl9tZW51UGFnZVswXSlcbiAgICAgICAgICAgIC53YWl0KGRlbGF5KVxuICAgICAgICAgICAgLnF1ZXVlKGJlaGluZFN0eWxlLCB7XG4gICAgICAgICAgICAgIGR1cmF0aW9uOiBkdXJhdGlvbixcbiAgICAgICAgICAgICAgdGltaW5nOiB0aGlzLnRpbWluZ1xuICAgICAgICAgICAgfSlcbiAgICAgICAgICAgIC5xdWV1ZShmdW5jdGlvbihkb25lKSB7XG4gICAgICAgICAgICAgIGRvbmUoKTtcbiAgICAgICAgICAgIH0pXG4gICAgICAgICAgICAucGxheSgpO1xuXG4gICAgICAgIH0uYmluZCh0aGlzKSwgMTAwMCAvIDYwKTtcbiAgICAgIH0sXG5cbiAgICAgIC8qKlxuICAgICAgICogQHBhcmFtIHtPYmplY3R9IG9wdGlvbnNcbiAgICAgICAqIEBwYXJhbSB7TnVtYmVyfSBvcHRpb25zLmRpc3RhbmNlXG4gICAgICAgKiBAcGFyYW0ge051bWJlcn0gb3B0aW9ucy5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ENvbG9yOiAnYmxhY2snLFxuICAgICAgICAgIHRvcDogJzBweCcsXG4gICAgICAgICAgbGVmdDogJzBweCcsXG4gICAgICAgICAgcmlnaHQ6ICcwcHgnLFxuICAgICAgICAgIGJvdHRvbTogJzBweCcsXG4gICAgICAgICAgcG9zaXRpb246ICdhYnNvbHV0ZScsXG4gICAgICAgICAgZGlzcGxheTogJ25vbmUnXG4gICAgICAgIH0pO1xuXG4gICAgICAgIGVsZW1lbnQucHJlcGVuZCh0aGlzLl9ibGFja01hc2spO1xuXG4gICAgICAgIC8vIERpcnR5IGZpeCBmb3IgYnJva2VuIHJlbmRlcmluZyBidWcgb24gYW5kcm9pZCA0LnguXG4gICAgICAgIGFuaW1pdChtYWluUGFnZVswXSkucXVldWUoe3RyYW5zZm9ybTogJ3RyYW5zbGF0ZTNkKDAsIDAsIDApJ30pLnBsYXkoKTtcbiAgICAgIH0sXG5cbiAgICAgIC8qKlxuICAgICAgICogQHBhcmFtIHtPYmplY3R9IG9wdGlvbnNcbiAgICAgICAqIEBwYXJhbSB7Qm9vbGVhbn0gb3B0aW9ucy5pc09wZW5lZFxuICAgICAgICogQHBhcmFtIHtTdHJpbmd9IG9wdGlvbnMud2lkdGhcbiAgICAgICAqL1xuICAgICAgb25SZXNpemVkOiBmdW5jdGlvbihvcHRpb25zKSB7XG4gICAgICAgIHRoaXMuX3dpZHRoID0gb3B0aW9ucy53aWR0aDtcbiAgICAgICAgdGhpcy5fbWVudVBhZ2UuY3NzKCd3aWR0aCcsIHRoaXMuX3dpZHRoKTtcblxuICAgICAgICBpZiAob3B0aW9ucy5pc09wZW5lZCkge1xuICAgICAgICAgIHZhciBtYXggPSB0aGlzLl9tZW51UGFnZVswXS5jbGllbnRXaWR0aDtcblxuICAgICAgICAgIHZhciBhYm92ZVRyYW5zZm9ybSA9IHRoaXMuX2dlbmVyYXRlQWJvdmVQYWdlVHJhbnNmb3JtKG1heCk7XG4gICAgICAgICAgdmFyIGJlaGluZFN0eWxlID0gdGhpcy5fZ2VuZXJhdGVCZWhpbmRQYWdlU3R5bGUobWF4KTtcblxuICAgICAgICAgIGFuaW1pdCh0aGlzLl9tYWluUGFnZVswXSkucXVldWUoe3RyYW5zZm9ybTogYWJvdmVUcmFuc2Zvcm19KS5wbGF5KCk7XG4gICAgICAgICAgYW5pbWl0KHRoaXMuX21lbnVQYWdlWzBdKS5xdWV1ZShiZWhpbmRTdHlsZSkucGxheSgpO1xuICAgICAgICB9XG4gICAgICB9LFxuXG4gICAgICAvKipcbiAgICAgICAqIEBwYXJhbSB7anFMaXRlfSBlbGVtZW50IFwib25zLXNsaWRpbmctbWVudVwiIG9yIFwib25zLXNwbGl0LXZpZXdcIiBlbGVtZW50XG4gICAgICAgKiBAcGFyYW0ge2pxTGl0ZX0gbWFpblBhZ2VcbiAgICAgICAqIEBwYXJhbSB7anFMaXRlfSBtZW51UGFnZVxuICAgICAgICovXG4gICAgICBkZXN0cm95OiBmdW5jdGlvbigpIHtcbiAgICAgICAgaWYgKHRoaXMuX2JsYWNrTWFzaykge1xuICAgICAgICAgIHRoaXMuX2JsYWNrTWFzay5yZW1vdmUoKTtcbiAgICAgICAgICB0aGlzLl9ibGFja01hc2sgPSBudWxsO1xuICAgICAgICB9XG5cbiAgICAgICAgaWYgKHRoaXMuX21haW5QYWdlKSB7XG4gICAgICAgICAgdGhpcy5fbWFpblBhZ2UuYXR0cignc3R5bGUnLCAnJyk7XG4gICAgICAgIH1cblxuICAgICAgICBpZiAodGhpcy5fbWVudVBhZ2UpIHtcbiAgICAgICAgICB0aGlzLl9tZW51UGFnZS5hdHRyKCdzdHlsZScsICcnKTtcbiAgICAgICAgfVxuXG4gICAgICAgIHRoaXMuX21haW5QYWdlID0gdGhpcy5fbWVudVBhZ2UgPSB0aGlzLl9lbGVtZW50ID0gdW5kZWZpbmVkO1xuICAgICAgfSxcblxuICAgICAgLyoqXG4gICAgICAgKiBAcGFyYW0ge0Z1bmN0aW9ufSBjYWxsYmFja1xuICAgICAgICogQHBh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RvbmUoKTtcbiAgICAgICAgICAgIH0pXG4gICAgICAgICAgICAucGxheSgpO1xuXG4gICAgICAgICAgYW5pbWl0KHRoaXMuX21lbnVQYWdlWzBdKVxuICAgICAgICAgICAgLndhaXQoZGVsYXkpXG4gICAgICAgICAgICAucXVldWUoYmVoaW5kU3R5bGUsIHtcbiAgICAgICAgICAgICAgZHVyYXRpb246IGR1cmF0aW9uLFxuICAgICAgICAgICAgICB0aW1pbmc6IHRoaXMudGltaW5nXG4gICAgICAgICAgICB9KVxuICAgICAgICAgICAgLnBsYXkoKTtcblxuICAgICAgICB9LmJpbmQodGhpcyksIDEwMDAgLyA2MCk7XG4gICAgICB9LFxuXG4gICAgICAvKipcbiAgICAgICAqIEBwYXJhbSB7RnVuY3Rpb259IGNhbGxiYWNrXG4gICAgICAgKiBAcGFyYW0ge0Jvb2xlYW59IGluc3RhbnRcbiAgICAgICAqL1xuICAgICAgY2xvc2VNZW51OiBmdW5jdGlvbihjYWxsYmFjaywgaW5zdGFudCkge1xuICAgICAgICB2YXIgZHVyYXRpb24gPSBpbnN0YW50ID09PSB0cnVlID8gMC4wIDogdGhpcy5kdXJhdGlvbjtcbiAgICAgICAgdmFyIGRlbGF5ID0gaW5zdGFudCA9PT0gdHJ1ZSA/IDAuMCA6IHRoaXMuZGVsYXk7XG5cbiAgICAgICAgdGhpcy5fYmxhY2tNYXNrLmNzcygnZGlzcGxheScsICdibG9jaycpO1xuXG4gICAgICAgIHZhciBhYm92ZVRyYW5zZm9ybSA9IHRoaXMuX2dlbmVyYXRlQWJvdmVQYWdlVHJhbnNmb3JtKDApO1xuICAgICAgICB2YXIgYmVoaW5kU3R5bGUgPSB0aGlzLl9nZW5lcmF0ZUJlaGluZFBhZ2VTdHlsZSgwKTtcblxuICAgICAgICBzZXRUaW1lb3V0KGZ1bmN0aW9uKCkge1xuXG4gICAgICAgICAgYW5pbWl0KHRoaXMuX21haW5QYWdlWzBdKVxuICAgICAgICAgICAgLndhaXQoZGVsYXkpXG4gICAgICAgICAgICAucXVldWUoe1xuICAgICAgICAgICAgICB0cmFuc2Zvcm06IGFib3ZlVHJhbnNmb3JtXG4gICAgICAgICAgICB9LCB7XG4gICAgICAgICAgICAgIGR1cmF0aW9uOiBkdXJhdGlvbixcbiAgICAgICAgICAgICAgdGltaW5nOiB0aGlzLnRpbWluZ1xuICAgICAgICAgICAgfSlcbiAgICAgICAgICAgIC5xdWV1ZSh7XG4gICAgICAgICAgICAgIHRyYW5zZm9ybTogJ3RyYW5zbGF0ZTNkKDAsIDAsIDApJ1xuICAgICAgICAgICAgfSlcbiAgICAgICAgICAgIC5xdWV1ZShmdW5jdGlvbihkb25lKSB7XG4gICAgICAgICAgICAgIHRoaXMuX21lbnVQYWdlLmNzcygnZGlzcGxheScsICdub25lJyk7XG4gICAgICAgICAgICAgIGNhbGxiYWNrKCk7XG4gICAgICAgICAgICAgIGRvbmUoKTtcbiAgICAgICAgICAgIH0uYmluZCh0aGlzKSlcbiAgICAgICAgICAgIC5wbGF5KCk7XG5cbiAgICAgICAgICBhbmltaXQodGhpcy5fbWVudVBhZ2VbMF0pXG4gICAgICAgICAgICAud2FpdChkZWxheSlcbiAgICAgICAgICAgIC5xdWV1ZShiZWhpbmRTdHlsZSwge1xuICAgICAgICAgICAgICBkdXJhdGlvbjogZHVyYXRpb24sXG4gICAgICAgICAgICAgIHRpbWluZzogdGhpcy50aW1pbmdcbiAgICAgICAgICAgIH0pXG4gICAgICAgICAgICAucXVldWUoZnVuY3Rpb24oZG9uZSkge1xuICAgICAgICAgICAgICBkb25lKCk7XG4gICAgICAgICAgICB9KVxuICAgICAgICAgICAgLnBsYXkoKTtcblxuICAgICAgICB9LmJpbmQodGhpcyksIDEwMDAgLyA2MCk7XG4gICAgICB9LFxuXG4gICAgICAvKipcbiAgICAgICAqIEBwYXJhbSB7T2JqZWN0fSBvcHRpb25zXG4gICAgICAgKiBAcGFyYW0ge051bWJlcn0gb3B0aW9ucy5kaXN0YW5jZVxuICAgICAgICogQHB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saXRWaWV3buOBruW5heOBp+OBmeOAglsvamFdXG4gKiBAcGFyYW0ge1N0cmluZ30gZXZlbnQub3JpZW50YXRpb25cbiAqICAgW2VuXUN1cnJlbnQgb3JpZW50YXRpb24uWy9lbl1cbiAqICAgW2phXeePvuWcqOOBrueUu+mdouOBruOCquODquOCqOODs+ODhuODvOOCt+ODp+ODs+OCkui/lOOBl+OBvuOBmeOAglwicG9ydHJhaXRcIuOCguOBl+OBj+OBr1wibGFuZHNjYXBlXCLjgafjgZnjgIJbL2phXVxuICovXG5cbi8qKlxuICogQGV2ZW50IHByZWNvbGxhcHNlXG4gKiBAZGVzY3JpcHRpb25cbiAqICAgW2VuXUZpcmVkIGp1c3QgYmVmb3JlIHRoZSB2aWV3IGlzIGNvbGxhcHNlZC5bL2VuXVxuICogICBbamFdY29sbGFwc2XnirbmhYvjgavjgarjgovliY3jgavnmbrngavjgZfjgb7jgZnjgIJbL2phXVxuICogQHBhcmFtIHtPYmplY3R9IGV2ZW50XG4gKiAgIFtlbl1FdmVudCBvYmplY3QuWy9lbl1cbiAqICAgW2phXeOCpOODmeODs+ODiOOCquODluOCuOOCp+OCr+ODiOOAglsvamFdXG4gKiBAcGFyYW0ge09iamVjdH0gZXZlbnQuc3BsaXRWaWV3XG4gKiAgIFtlbl1TcGxpdCB2aWV3IG9iamVjdC5bL2VuXVxuICogICBbamFd44Kk44OZ44Oz44OI44GM55m654Gr44GX44GfU3BsaXRWaWV344Kq44OW44K444Kn44Kv44OI44Gn44GZ44CCWy9qYV1cbiAqIEBwYXJhbSB7TnVtYmVyfSBldmVudC53aWR0aFxuICogICBbZW5dQ3VycmVudCB3aWR0aC5bL2VuXVxuICogICBbamFd54++5Zyo44GuU3BsaXRWaWV3buOBruW5heOBp+OBmeOAglsvamFdXG4gKiBAcGFyYW0ge1N0cmluZ30gZXZlbnQub3JpZW50YXRpb25cbiAqICAgW2VuXUN1cnJlbnQgb3JpZW50YXRpb24uWy9lbl1cbiAqICAgW2phXeePvuWcqOOBrueUu+mdouOBruOCquODquOCqOODs+ODhuODvOOCt+ODp+ODs+OCkui/lOOBl+OBvuOBmeOAglwicG9ydHJhaXRcIuOCguOBl+OBj+OBr1wibGFuZHNjYXBlXCLjgafjgZnjgIJbL2phXVxuICovXG5cbi8qKlxuICogQGV2ZW50IHBvc3Rjb2xsYXBzZVxuICogQGRlc2NyaXB0aW9uXG4gKiAgIFtlbl1GaXJlZCBqdXN0IGFmdGVyIHRoZSB2aWV3IGlzIGNvbGxhcHNlZC5bL2VuXVxuICogICBbamFdY29sbGFwc2XnirbmhYvjgavjgarjgaPjgZ/lvozjgavnmbrngavjgZfjgb7jgZnjgIJbL2phXVxuICogQHBhcmFtIHtPYmplY3R9IGV2ZW50XG4gKiAgIFtlbl1FdmVudCBvYmplY3QuWy9lbl1cbiAqICAgW2phXeOCpOODmeODs+ODiOOCquODluOCuOOCp+OCr+ODiOOAglsvamFdXG4gKiBAcGFyYW0ge09iamVjdH0gZXZlbnQuc3BsaXRWaWV3XG4gKiAgIFtlbl1TcGxpdCB2aWV3IG9iamVjdC5bL2VuXVxuICogICBbamFd44Kk44OZ44Oz44OI44GM55m654Gr44GX44GfU3BsaXRWaWV344Kq44OW44K444Kn44Kv44OI44Gn44GZ44CCWy9qYV1cbiAqIEBwYXJhbSB7TnVtYmVyfSBldmVudC53aWR0aFxuICogICBbZW5dQ3VycmVudCB3aWR0aC5bL2VuXVxuICogICBbamFd54++5Zyo44GuU3BsaXRWaWV3buOBruW5heOBp+OBmeOAglsvamFdXG4gKiBAcGFyYW0ge1N0cmluZ30gZXZlbnQub3JpZW50YXRpb25cbiAqICAgW2VuXUN1cnJlbnQgb3JpZW50YXRpb24uWy9lbl1cbiAqICAgW2phXeePvuWcqOOBrueUu+mdouOBruOCquODquOCqOODs+ODhuODvOOCt+ODp+ODs+OCkui/lOOBl+OBvuOBmeOAglwicG9ydHJhaXRcIuOCguOBl+OBj+OBr1wibGFuZHNjYXBlXCLjgafjgZnjgIJbL2phXVx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A9IHVuZGVmaW5lZDtcbiAgICAgICAgICAgICAgJG9uc2VuLnJlbW92ZU1vZGlmaWVyTWV0aG9kcyhiYWNrQnV0dG9uKTtcbiAgICAgICAgICAgICAgZWxlbWVudCA9IG51bGw7XG4gICAgICAgICAgICB9KTtcblxuICAgICAgICAgICAgQ29tcG9uZW50Q2xlYW5lci5vbkRlc3Ryb3koc2NvcGUsIGZ1bmN0aW9uKCkge1xuICAgICAgICAgICAgICBDb21wb25lbnRDbGVhbmVyLmRlc3Ryb3lTY29wZShzY29wZSk7XG4gICAgICAgICAgICAgIENvbXBvbmVudENsZWFuZXIuZGVzdHJveUF0dHJpYnV0ZXMoYXR0cnMpO1xuICAgICAgICAgICAgICBlbGVtZW50ID0gc2NvcGUgPSBhdHRycyA9IG51bGw7XG4gICAgICAgICAgICB9KTtcbiAgICAgICAgICB9LFxuICAgICAgICAgIHBvc3Q6IGZ1bmN0aW9uKHNjb3BlLCBlbGVtZW50KSB7XG4gICAgICAgICAgICAkb25zZW4uZmlyZUNvbXBvbmVudEV2ZW50KGVsZW1lbnRbMF0sICdpbml0Jyk7XG4gICAgICAgICAgfVxuICAgICAgICB9O1xuICAgICAgfVxuICAgIH07XG4gIH0pO1xufSkoKTtcbiIsIihmdW5jdGlvbigpe1xuICAndXNlIHN0cmljdCc7XG5cbiAgYW5ndWxhci5tb2R1bGUoJ29uc2VuJykuZGlyZWN0aXZlKCdvbnNCb3R0b21Ub29sYmFyJywgZnVuY3Rpb24oJG9uc2VuLCBHZW5lcmljVmlldykge1xuICAgIHJldHVybiB7XG4gICAgICByZXN0cmljdDogJ0UnLFxuICAgICAgbGluazoge1xuICAgICAgICBwcmU6IGZ1bmN0aW9uKHNjb3BlLCBlbGVtZW50LCBhdHRycykge1xuICAgICAgICAgIEN1c3RvbUVsZW1lbnRzLnVwZ3JhZGUoZWxlbWVudFswXSk7XG4gICAgICAgICAgR2VuZXJpY1ZpZXcucmVnaXN0ZXIoc2NvcGUsIGVsZW1lbnQsIG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k7XG4gICAgICAgICAgfSk7XG5cbiAgICAgICAgICB2YXIgaGFuZGxlciA9IGZ1bmN0aW9uKGV2ZW50KSB7XG4gICAgICAgICAgICB2YXIgYXR0ciA9ICduZycgKyB0aXRsaXplKGV2ZW50LnR5cGUpO1xuXG4gICAgICAgICAgICBpZiAoYXR0ciBpbiBzY29wZURlZikge1xuICAgICAgICAgICAgICBzY29wZVthdHRyXSh7JGV2ZW50OiBldmVudH0pO1xuICAgICAgICAgICAgfVxuICAgICAgICAgIH07XG5cbiAgICAgICAgICB2YXIgZ2VzdHVyZURldGVjdG9yO1xuXG4gICAgICAgICAgc2V0SW1tZWRpYXRlKGZ1bmN0aW9uKCkge1xuICAgICAgICAgICAgZ2VzdHVyZURldGVjdG9yID0gZWxlbWVudFswXS5fZ2VzdHVyZURldGVjdG9yO1xuICAgICAgICAgICAgZ2VzdHVyZURldGVjdG9yLm9uKEVWRU5UUy5qb2luKCcgJyksIGhhbmRsZXIpO1xuICAgICAgICAgIH0pO1xuXG4gICAgICAgICAgJG9uc2VuLmNsZWFuZXIub25EZXN0cm95KHNjb3BlLCBmdW5jdGlvbigpIHtcbiAgICAgICAgICAgIGdlc3R1cmVEZXRlY3Rvci5vZmYoRVZFTlRTLmpvaW4oJyAnKSwgaGFuZGxlcik7XG4gICAgICAgICAgICAkb25zZW4uY2xlYXJDb21wb25lbnQoe1xuICAgICAgICAgICAgICBzY29wZTogc2NvcGUsXG4gICAgICAgICAgICAgIGVsZW1lbnQ6IGVsZW1lbnQsXG4gICAgICAgICAgICAgIGF0dHJzOiBhdHRyc1xuICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICBnZXN0dXJlRGV0ZWN0b3IuZWxlbWVudCA9IHNjb3BlID0gZWxlbWVudCA9IGF0dHJzID0gbnVsbDtcbiAgICAgICAgICB9KTtcblxuICAgICAgICAgICRvbnNlbi5maXJlQ29tcG9uZW50RXZlbnQoZWxlbWVudFswXSwgJ2luaXQnKTtcbiAgICAgICAgfTtcbiA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RlKTtcblxuICAgICAgICAgIHVwZGF0ZSgpO1xuXG4gICAgICAgICAgJG9uc2VuLmNsZWFuZXIub25EZXN0cm95KHNjb3BlLCBmdW5jdGlvbigpIHtcbiAgICAgICAgICAgICRvbnNHbG9iYWwub3JpZW50YXRpb24ub2ZmKCdjaGFuZ2UnLCB1cGRhdGUpO1xuXG4gICAgICAgICAgICAkb25zZW4uY2xlYXJDb21wb25lbnQoe1xuICAgICAgICAgICAgICBlbGVtZW50OiBlbGVtZW50LFxuICAgICAgICAgICAgICBzY29wZTogc2NvcGUsXG4gICAgICAgICAgICAgIGF0dHJzOiBhdHRyc1xuICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICBlbGVtZW50ID0gc2NvcGUgPSBhdHRycyA9IG51bGw7XG4gICAgICAgICAgfSk7XG5cbiAgICAgICAgICBmdW5jdGlvbiB1cGRhdGUoKSB7XG4gICAgICAgICAgICB2YXIgdXNlck9yaWVudGF0aW9uID0gKCcnICsgYXR0cnMub25zSWZPcmllbnRhdGlvbikudG9Mb3dlckNhc2UoKTtcbiAgICAgICAgICAgIHZhciBvcmllbnRhdGlvbiA9IGdldExhbmRzY2FwZU9yUG9ydHJhaXQoKTtcblxuICAgICAgICAgICAgaWYgKHVzZXJPcmllbnRhdGlvbiA9PT0gJ3BvcnRyYWl0JyB8fCB1c2VyT3JpZW50YXRpb24gPT09ICdsYW5kc2NhcGUnKSB7XG4gICAgICAgICAgICAgIGlmICh1c2VyT3JpZW50YXRpb24gPT09IG9yaWVudGF0aW9uKSB7XG4gICAgICAgICAgICAgICAgZWxlbWVudC5jc3MoJ2Rpc3BsYXknLCAnJyk7XG4gICAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgICAgZWxlbWVudC5jc3MoJ2Rpc3BsYXknLCAnbm9uZScpO1xuICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgZnVuY3Rpb24gZ2V0TGFuZHNjYXBlT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RnZSc7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgdmFyIGlzQ2hyb21lID0gISF3aW5kb3cuY2hyb21lICYmICFpc09wZXJhICYmICFpc0VkZ2U7IC8vIENocm9tZSAxK1xuICAgICAgICAgIGlmIChpc0Nocm9tZSkge1xuICAgICAgICAgICAgcmV0dXJuICdjaHJvbWUnO1xuICAgICAgICAgIH1cblxuICAgICAgICAgIHZhciBpc0lFID0gLypAY2Nfb24hQCovZmFsc2UgfHwgISFkb2N1bWVudC5kb2N1bWVudE1vZGU7IC8vIEF0IGxlYXN0IElFNlxuICAgICAgICAgIGlmIChpc0lFKSB7XG4gICAgICAgICAgICByZXR1cm4gJ2llJztcbiAgICAgICAgICB9XG5cbiAgICAgICAgICByZXR1cm4gJ3Vua25vd24nO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfTtcbiAgfSk7XG59KSgpO1xuIiwiLyoqXG4gKiBAbmdkb2MgZGlyZWN0aXZlXG4gKiBAaWQgaW5wdXRcbiAqIEBuYW1lIG9ucy1pbnB1dFxuICogQGNhdGVnb3J5IGZvcm1cbiAqIEBkZXNjcmlwdGlvblxuICogIFtlbl1JbnB1dCBjb21wb25lbnQuWy9lbl1cbiAqICBbamFdaW5wdXTjgrPjg7Pjg53igJXjg43jg7Pjg4jjgafjgZnjgIJbL2phXVxuICogQGNvZGVwZW4gb2pReExqXG4gKiBAZ3VpZGUgVXNpbmdGb3JtQ29tcG9uZW50c1xuICogICBbZW5dVXNpbmcgZm9ybSBjb21wb25lbnRzWy9lbl1cbiAqICAgW2phXeODleOCqeODvOODoOOCkuS9v+OBhlsvamFdXG4gKiBAZ3VpZGUgRXZlbnRIYW5kbGluZ1xuICogICBbZW5dRXZlbnQgaGFuZGxpbmcgZGVzY3JpcHRpb25zWy9lbl1cbiAqICAgW2phXeOCpOODmeODs+ODiOWHpueQhuOBruS9v+OBhOaWuVsvamFdXG4gKiBAZXhhbXBsZVxuICogPG9ucy1pbnB1dD48L29ucy1pbnB1d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ICAgICAgIHNldChzY29wZSwgZWwudmFsdWUpO1xuICAgICAgICAgIH1cbiAgICAgICAgICBlbHNlIGlmIChlbC50eXBlID09PSAncmFkaW8nICYmIGVsLmNoZWNrZWQpIHtcbiAgICAgICAgICAgIHNldChzY29wZSwgZWwudmFsdWUpO1xuICAgICAgICAgIH1cbiAgICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgIHNldChzY29wZSwgZWwuY2hlY2tlZCk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKGF0dHJzLm5nQ2hhbmdlKSB7XG4gICAgICAgICAgICBzY29wZS4kZXZhbChhdHRycy5uZ0NoYW5nZSk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgc2NvcGUuJHBhcmVudC4kZXZhbEFzeW5jKCk7XG4gICAgICAgIH07XG5cbiAgICAgICAgaWYgKGF0dHJzLm5nTW9kZWwpIHtcbiAgICAgICAgICBzY29wZS4kd2F0Y2goYXR0cnMubmdNb2RlbCwgKHZhbHVlKSA9PiB7XG4gICAgICAgICAgICBpZiAoZWwuX2lzVGV4dElucHV0KSB7XG4gICAgICAgICAgICAgIGVsLnZhbHVlID0gdmFsdWU7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIGlmIChlbC50eXBlID09PSAncmFkaW8nKSB7XG4gICAgICAgICAgICAgIGVsLmNoZWNrZWQgPSB2YWx1ZSA9PT0gZWwudmFsdWU7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgICAgZWwuY2hlY2tlZCA9IHZhbHVlO1xuICAgICAgICAgICAgfVxuICAgICAgICAgIH0pO1xuXG4gICAgICAgICAgZWwuX2lzVGV4dElucHV0XG4gICAgICAgICAgICA/IGVsZW1lbnQub24oJ2lucHV0Jywgb25JbnB1dClcbiAgICAgICAgICAgIDogZWxlbWVudC5vbignY2hhbmdlJywgb25JbnB1dCk7XG4gICAgICAgIH1cblxuICAgICAgICBzY29wZS4kb24oJyRkZXN0cm95JywgKCkgPT4ge1xuICAgICAgICAgIGVsLl9pc1RleHRJbnB1dFxuICAgICAgICAgICAgPyBlbGVtZW50Lm9mZignaW5wdXQnLCBvbklucHV0KVxuICAgICAgICAgICAgOiBlbGVtZW50Lm9mZignY2hhbmdlJywgb25JbnB1dCk7XG5cbiAgICAgICAgICBzY29wZSA9IGVsZW1lbnQgPSBhdHRycyA9IGVsID0gbnVsbDtcbiAgICAgICAgfSk7XG4gICAgICB9XG4gICAgfTtcbiAgfSk7XG59KSgpO1xuIiwiLyoqXG4gKiBAZWxlbWVudCBvbnMta2V5Ym9hcmQtYWN0aXZlXG4gKiBAY2F0ZWdvcnkgZm9ybVxuICogQGRlc2NyaXB0aW9uXG4gKiAgIFtlbl1cbiAqICAgICBDb25kaXRpb25hbGx5IGRpc3BsYXkgY29udGVudCBkZXBlbmRpbmcgb24gaWYgdGhlIHNvZnR3YXJlIGtleWJvYXJkIGlzIHZpc2libGUgb3IgaGlkZGVuLlxuICogICAgIFRoaXMgY29tcG9uZW50IHJlcXVpcmVzIGNvcmRvdmEgYW5kIHRoYXQgdGhlIGNvbS5pb25pYy5rZXlib2FyZCBwbHVnaW4gaXMgaW5zdGFsbGVkLlxuICogICBbL2VuXVxuICogICBbamFdXG4gKiAgICAg44K944OV44OI44Km44Kn44Ki44Kt44O844Oc44O844OJ44GM6KGo56S644GV44KM44Gm44GE44KL44GL44Gp44GG44GL44Gn44CB44Kz44Oz44OG44Oz44OE44KS6KGo56S644GZ44KL44GL44Gp44GG44GL44KS5YiH44KK5pu/44GI44KL44GT44Go44GM5Ye65p2l44G+44GZ44CCXG4gKiAgICAg44GT44Gu44Kz44Oz44Od44O844ON44Oz44OI44Gv44CBQ29yZG92YeOChGNvbS5pb25pYy5rZXlib2FyZOODl+ODqeOCsOOCpOODs+OCkuW/heimgeOBqOOBl+OBvuOBmeOAglxuICogICBbL2phXVxuICogQGd1aWRlIFV0aWxpdHlBUElzXG4gKiAgIFtlbl1PdGhlciB1dGl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gICAgdmFyIG5nRXZlbnREaXJlY3RpdmVzID0ge307XG4gICAgJ2NsaWNrIGRibGNsaWNrIG1vdXNlZG93biBtb3VzZXVwIG1vdXNlb3ZlciBtb3VzZW91dCBtb3VzZW1vdmUgbW91c2VlbnRlciBtb3VzZWxlYXZlIGtleWRvd24ga2V5dXAga2V5cHJlc3Mgc3VibWl0IGZvY3VzIGJsdXIgY29weSBjdXQgcGFzdGUnLnNwbGl0KCcgJykuZm9yRWFjaChcbiAgICAgIGZ1bmN0aW9uKG5hbWUpIHtcbiAgICAgICAgdmFyIGRpcmVjdGl2ZU5hbWUgPSBkaXJlY3RpdmVOb3JtYWxpemUoJ25nLScgKyBuYW1lKTtcbiAgICAgICAgbmdFdmVudERpcmVjdGl2ZXNbZGlyZWN0aXZlTmFtZV0gPSBbJyRwYXJzZScsIGZ1bmN0aW9uKCRwYXJzZSkge1xuICAgICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBjb21waWxlOiBmdW5jdGlvbigkZWxlbWVudCwgYXR0cikge1xuICAgICAgICAgICAgICB2YXIgZm4gPSAkcGFyc2UoYXR0cltkaXJlY3RpdmVOYW1lXSk7XG4gICAgICAgICAgICAgIHJldHVybiBmdW5jdGlvbihzY29wZSwgZWxlbWVudCwgYXR0cikge1xuICAgICAgICAgICAgICAgIHZhciBsaXN0ZW5lciA9IGZ1bmN0aW9uKGV2ZW50KSB7XG4gICAgICAgICAgICAgICAgICBzY29wZS4kYXBwbHkoZnVuY3Rpb24oKSB7XG4gICAgICAgICAgICAgICAgICAgIGZuKHNjb3BlLCB7JGV2ZW50OiBldmVudH0pO1xuICAgICAgICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICAgICAgfTtcbiAgICAgICAgICAgICAgICBlbGVtZW50Lm9uKG5hbWUsIGxpc3RlbmVyKTtcblxuICAgICAgICAgICAgICAgIENvbXBvbmVudENsZWFuZXIub25EZXN0cm95KHNjb3BlLCBmdW5jdGlvbigpIHtcbiAgICAgICAgICAgICAgICAgIGVsZW1lbnQub2ZmKG5hbWUsIGxpc3RlbmVyKTtcbiAgICAgICAgICAgICAgICAgIGVsZW1lbnQgPSBudWxsO1xuXG4gICAgICAgICAgICAgICAgICBDb21wb25lbnRDbGVhbmVyLmRlc3Ryb3lTY29wZShzY29wZSk7XG4gICAgICAgICAgICAgICAgICBzY29wZSA9IG51bGw7XG5cbiAgICAgICAgICAgICAgICAgIENvbXBvbmVudENsZWFuZXIuZGVzdHJveUF0dHJpYnV0ZXMoYXR0cik7XG4gICAgICAgICAgICAgICAgICBhdHRyID0gbnVsbDtcbiAgICAgICAgICAgICAgICB9KTtcbiAgICAgICAgICAgICAgfTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICB9O1xuICAgICAgICB9XTtcblxuICAgICAgICBmdW5jdGlvbiBkaXJlY3RpdmVOb3JtYWxpemUobmFtZSkge1xuICAgICAgICAgIHJldHVybiBuYW1lLnJlcGxhY2UoLy0oW2Etel0pL2csIGZ1bmN0aW9uKG1hdGNoZXMpIHtcbiAgICAgICAgICAgIHJldHVybiBtYXRjaGVzWzFdLnRvVXBwZXJDYXNlKCk7XG4gICAgICAgICAgfSk7XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICApO1xuICAgIG1vZHVsZS5jb25maWcoZnVuY3Rpb24oJHByb3ZpZGUpIHtcbiAgICAgIHZhciBzaGlmdCA9IGZ1bmN0aW9uKCRkZWxlZ2F0ZSkge1xuICAgICAgICAkZGVsZWdhdGUuc2hpZnQoKTtcbiAgICAgICAgcmV0dXJuICRkZWxlZ2F0ZTtcbiAgICAgIH07XG4gICAgICBPYmplY3Qua2V5cyhuZ0V2ZW50RGlyZWN0aXZlcykuZm9yRWFjaChmdW5jdGlvbihkaXJlY3RpdmVOYW1lKSB7XG4gICAgICAgICRwcm92aWRlLmRlY29yYXRvcihkaXJlY3RpdmVOYW1lICsgJ0RpcmVjdGl2ZScsIFsnJGRlbGVnYXRlJywgc2hpZnRdKTtcbiAgICAgIH0pO1xuICAgI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biAgICAgIH1cbiAgICB9XG4gIH0pO1xuXG59KSgpO1xuIl0sInNvdXJjZVJvb3QiOiIvc291cmNlLyJ9
node_modules/react-router/Route.js
ishan993/IshanBlogReactRedux
'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _warning = require('warning'); var _warning2 = _interopRequireDefault(_warning); var _invariant = require('invariant'); var _invariant2 = _interopRequireDefault(_invariant); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _matchPath = require('./matchPath'); var _matchPath2 = _interopRequireDefault(_matchPath); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var isEmptyChildren = function isEmptyChildren(children) { return _react2.default.Children.count(children) === 0; }; /** * The public API for matching a single path and rendering. */ var Route = function (_React$Component) { _inherits(Route, _React$Component); function Route() { var _temp, _this, _ret; _classCallCheck(this, Route); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = { match: _this.computeMatch(_this.props, _this.context.router) }, _temp), _possibleConstructorReturn(_this, _ret); } Route.prototype.getChildContext = function getChildContext() { return { router: _extends({}, this.context.router, { route: { location: this.props.location || this.context.router.route.location, match: this.state.match } }) }; }; Route.prototype.computeMatch = function computeMatch(_ref, router) { var computedMatch = _ref.computedMatch, location = _ref.location, path = _ref.path, strict = _ref.strict, exact = _ref.exact, sensitive = _ref.sensitive; if (computedMatch) return computedMatch; // <Switch> already computed the match for us (0, _invariant2.default)(router, 'You should not use <Route> or withRouter() outside a <Router>'); var route = router.route; var pathname = (location || route.location).pathname; return path ? (0, _matchPath2.default)(pathname, { path: path, strict: strict, exact: exact, sensitive: sensitive }) : route.match; }; Route.prototype.componentWillMount = function componentWillMount() { (0, _warning2.default)(!(this.props.component && this.props.render), 'You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored'); (0, _warning2.default)(!(this.props.component && this.props.children && !isEmptyChildren(this.props.children)), 'You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored'); (0, _warning2.default)(!(this.props.render && this.props.children && !isEmptyChildren(this.props.children)), 'You should not use <Route render> and <Route children> in the same route; <Route children> will be ignored'); }; Route.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps, nextContext) { (0, _warning2.default)(!(nextProps.location && !this.props.location), '<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.'); (0, _warning2.default)(!(!nextProps.location && this.props.location), '<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.'); this.setState({ match: this.computeMatch(nextProps, nextContext.router) }); }; Route.prototype.render = function render() { var match = this.state.match; var _props = this.props, children = _props.children, component = _props.component, render = _props.render; var _context$router = this.context.router, history = _context$router.history, route = _context$router.route, staticContext = _context$router.staticContext; var location = this.props.location || route.location; var props = { match: match, location: location, history: history, staticContext: staticContext }; return component ? // component prop gets first priority, only called if there's a match match ? _react2.default.createElement(component, props) : null : render ? // render prop is next, only called if there's a match match ? render(props) : null : children ? // children come last, always called typeof children === 'function' ? children(props) : !isEmptyChildren(children) ? _react2.default.Children.only(children) : null : null; }; return Route; }(_react2.default.Component); Route.propTypes = { computedMatch: _propTypes2.default.object, // private, from <Switch> path: _propTypes2.default.string, exact: _propTypes2.default.bool, strict: _propTypes2.default.bool, sensitive: _propTypes2.default.bool, component: _propTypes2.default.func, render: _propTypes2.default.func, children: _propTypes2.default.oneOfType([_propTypes2.default.func, _propTypes2.default.node]), location: _propTypes2.default.object }; Route.contextTypes = { router: _propTypes2.default.shape({ history: _propTypes2.default.object.isRequired, route: _propTypes2.default.object.isRequired, staticContext: _propTypes2.default.object }) }; Route.childContextTypes = { router: _propTypes2.default.object.isRequired }; exports.default = Route;
ajax/libs/react-bootstrap/0.22.6/react-bootstrap.min.js
Amomo/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.ReactBootstrap=t(require("react")):e.ReactBootstrap=t(e.React)}(this,function(e){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(31),s=n(o),a=r(32),i=n(a),l=r(20),p=n(l),u=r(33),d=n(u),f=r(3),c=n(f),h=r(34),m=n(h),v=r(9),y=n(v),b=r(14),g=n(b),P=r(21),O=n(P),T=r(35),C=n(T),_=r(40),N=n(_),E=r(22),x=n(E),w=r(36),k=n(w),S=r(37),M=n(S),D=r(38),j=n(D),I=r(39),A=n(I),K=r(7),B=n(K),L=r(41),H=n(L),R=r(15),W=n(R),U=r(16),z=n(U),q=r(10),F=n(q),V=r(42),G=n(V),Y=r(43),Z=n(Y),Q=r(44),J=n(Q),X=r(25),$=n(X),ee=r(45),te=n(ee),re=r(46),ne=n(re),oe=r(47),se=n(oe),ae=r(48),ie=n(ae),le=r(49),pe=n(le),ue=r(50),de=n(ue),fe=r(26),ce=n(fe),he=r(52),me=n(he),ve=r(27),ye=n(ve),be=r(51),ge=n(be),Pe=r(53),Oe=n(Pe),Te=r(17),Ce=n(Te),_e=r(54),Ne=n(_e),Ee=r(57),xe=n(Ee),we=r(28),ke=n(we),Se=r(55),Me=n(Se),De=r(56),je=n(De),Ie=r(58),Ae=n(Ie),Ke=r(59),Be=n(Ke),Le=r(61),He=n(Le),Re=r(62),We=n(Re),Ue=r(63),ze=n(Ue),qe=r(65),Fe=n(qe),Ve=r(66),Ge=n(Ve),Ye=r(64),Ze=n(Ye),Qe=r(67),Je=n(Qe),Xe=r(68),$e=n(Xe),et=r(69),tt=n(et),rt=r(11),nt=n(rt);t["default"]={Accordion:s["default"],Affix:i["default"],AffixMixin:p["default"],Alert:d["default"],BootstrapMixin:c["default"],Badge:m["default"],Button:y["default"],ButtonGroup:g["default"],ButtonInput:O["default"],ButtonToolbar:C["default"],CollapsableNav:N["default"],CollapsibleNav:x["default"],Carousel:k["default"],CarouselItem:M["default"],Col:j["default"],CollapsableMixin:A["default"],CollapsibleMixin:B["default"],DropdownButton:H["default"],DropdownMenu:W["default"],DropdownStateMixin:z["default"],FadeMixin:F["default"],Glyphicon:G["default"],Grid:Z["default"],Input:J["default"],Interpolate:$["default"],Jumbotron:te["default"],Label:ne["default"],ListGroup:se["default"],ListGroupItem:ie["default"],MenuItem:pe["default"],Modal:de["default"],Nav:ce["default"],Navbar:me["default"],NavItem:ye["default"],ModalTrigger:ge["default"],OverlayTrigger:Oe["default"],OverlayMixin:Ce["default"],PageHeader:Ne["default"],Panel:xe["default"],PanelGroup:ke["default"],PageItem:Me["default"],Pager:je["default"],Popover:Ae["default"],ProgressBar:Be["default"],Row:He["default"],SplitButton:We["default"],SubNav:ze["default"],TabbedArea:Fe["default"],Table:Ge["default"],TabPane:Ze["default"],Thumbnail:Je["default"],Tooltip:$e["default"],Well:tt["default"],styleMaps:nt["default"]},e.exports=t["default"]},function(t,r,n){t.exports=e},function(e,t,r){/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function n(){"use strict";for(var e="",t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e+=" "+r;else if(Array.isArray(r))e+=" "+n.apply(null,r);else if("object"===o)for(var s in r)r.hasOwnProperty(s)&&r[s]&&(e+=" "+s)}}return e.substr(1)}var o,s;"undefined"!=typeof e&&e.exports&&(e.exports=n),o=[],s=function(){return n}.apply(t,o),!(void 0!==s&&(e.exports=s))},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(11),s=n(o),a=r(29),i=n(a),l={propTypes:{bsClass:i["default"].keyOf(s["default"].CLASSES),bsStyle:i["default"].keyOf(s["default"].STYLES),bsSize:i["default"].keyOf(s["default"].SIZES)},getBsClassSet:function(){var e={},t=this.props.bsClass&&s["default"].CLASSES[this.props.bsClass];if(t){e[t]=!0;var r=t+"-",n=this.props.bsSize&&s["default"].SIZES[this.props.bsSize];n&&(e[r+n]=!0);var o=this.props.bsStyle&&s["default"].STYLES[this.props.bsStyle];this.props.bsStyle&&(e[r+o]=!0)}return e},prefixClass:function(e){return s["default"].CLASSES[this.props.bsClass]+"-"+e}};t["default"]=l,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){var n=0;return p["default"].Children.map(e,function(e){if(p["default"].isValidElement(e)){var o=n;return n++,t.call(r,e,o)}return e})}function s(e,t,r){var n=0;return p["default"].Children.forEach(e,function(e){p["default"].isValidElement(e)&&(t.call(r,e,n),n++)})}function a(e){var t=0;return p["default"].Children.forEach(e,function(e){p["default"].isValidElement(e)&&t++}),t}function i(e){var t=!1;return p["default"].Children.forEach(e,function(e){!t&&p["default"].isValidElement(e)&&(t=!0)}),t}Object.defineProperty(t,"__esModule",{value:!0});var l=r(1),p=n(l);t["default"]={map:o,forEach:s,numberOf:a,hasValidComponent:i},e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=u["default"].findDOMNode(e);return t&&t.ownerDocument||document}function s(e){return o(e).defaultView.getComputedStyle(e,null)}function a(e){if(window.jQuery)return window.jQuery(e).offset();var t=o(e).documentElement,r={top:0,left:0};return"undefined"!=typeof e.getBoundingClientRect&&(r=e.getBoundingClientRect()),{top:r.top+window.pageYOffset-t.clientTop,left:r.left+window.pageXOffset-t.clientLeft}}function i(e,t){if(window.jQuery)return window.jQuery(e).position();var r=void 0,n={top:0,left:0};return"fixed"===s(e).position?r=e.getBoundingClientRect():(t||(t=l(e)),r=a(e),"HTML"!==t.nodeName&&(n=a(t)),n.top+=parseInt(s(t).borderTopWidth,10),n.left+=parseInt(s(t).borderLeftWidth,10)),{top:r.top-n.top-parseInt(s(e).marginTop,10),left:r.left-n.left-parseInt(s(e).marginLeft,10)}}function l(e){for(var t=o(e).documentElement,r=e.offsetParent||t;r&&"HTML"!==r.nodeName&&"static"===s(r).position;)r=r.offsetParent;return r||t}Object.defineProperty(t,"__esModule",{value:!0});var p=r(1),u=n(p);t["default"]={ownerDocument:o,getComputedStyles:s,getOffset:a,getPosition:i,offsetParent:l},e.exports=t["default"]},function(e,t,r){"use strict";function n(e,t){var r="function"==typeof e,n="function"==typeof t;return r||n?r?n?function(){e.apply(this,arguments),t.apply(this,arguments)}:e:t:null}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(18),i=n(a),l=r(8),p=n(l),u={propTypes:{defaultExpanded:s["default"].PropTypes.bool,expanded:s["default"].PropTypes.bool},getInitialState:function(){var e=null!=this.props.defaultExpanded?this.props.defaultExpanded:null!=this.props.expanded?this.props.expanded:!1;return{expanded:e,collapsing:!1}},componentWillUpdate:function(e,t){var r=null!=e.expanded?e.expanded:t.expanded;if(r!==this.isExpanded()){var n=this.getCollapsibleDOMNode(),o=this.dimension(),s="0";r||(s=this.getCollapsibleDimensionValue()),n.style[o]=s+"px",this._afterWillUpdate()}},componentDidUpdate:function(e,t){this._checkToggleCollapsing(e,t),this._checkStartAnimation()},_afterWillUpdate:function(){},_checkStartAnimation:function(){if(this.state.collapsing){var e=this.getCollapsibleDOMNode(),t=this.dimension(),r=this.getCollapsibleDimensionValue(),n=void 0;n=this.isExpanded()?r+"px":"0px",e.style[t]=n}},_checkToggleCollapsing:function(e,t){var r=null!=e.expanded?e.expanded:t.expanded,n=this.isExpanded();r!==n&&(r?this._handleCollapse():this._handleExpand())},_handleExpand:function(){var e=this,t=this.getCollapsibleDOMNode(),r=this.dimension(),n=function o(){e._removeEndEventListener(t,o),t.style[r]="",e.setState({collapsing:!1})};this._addEndEventListener(t,n),this.setState({collapsing:!0})},_handleCollapse:function(){var e=this,t=this.getCollapsibleDOMNode(),r=function n(){e._removeEndEventListener(t,n),e.setState({collapsing:!1})};this._addEndEventListener(t,r),this.setState({collapsing:!0})},_addEndEventListener:function(e,t){i["default"].addEndEventListener(e,t)},_removeEndEventListener:function(e,t){i["default"].removeEndEventListener(e,t)},dimension:function(){return"function"==typeof this.getCollapsableDimension?(p["default"]("CollapsableMixin.getCollapsableDimension()","CollapsibleMixin.getCollapsibleDimension()","https://github.com/react-bootstrap/react-bootstrap/issues/425#issuecomment-97110963"),this.getCollapsableDimension()):"function"==typeof this.getCollapsibleDimension?this.getCollapsibleDimension():"height"},isExpanded:function(){return null!=this.props.expanded?this.props.expanded:this.state.expanded},getCollapsibleClassSet:function(e){var t={};return"string"==typeof e&&e.split(" ").forEach(function(e){e&&(t[e]=!0)}),t.collapsing=this.state.collapsing,t.collapse=!this.state.collapsing,t["in"]=this.isExpanded()&&!this.state.collapsing,t}};t["default"]=u,e.exports=t["default"]},function(e,t,r){"use strict";function n(e,t,r){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=a["default"].createClass({displayName:"Button",mixins:[u["default"]],propTypes:{active:a["default"].PropTypes.bool,disabled:a["default"].PropTypes.bool,block:a["default"].PropTypes.bool,navItem:a["default"].PropTypes.bool,navDropdown:a["default"].PropTypes.bool,componentClass:a["default"].PropTypes.node,href:a["default"].PropTypes.string,target:a["default"].PropTypes.string},getDefaultProps:function(){return{bsClass:"button",bsStyle:"default",type:"button"}},render:function(){var e=this.props.navDropdown?{}:this.getBsClassSet(),t=void 0;return e=o({active:this.props.active,"btn-block":this.props.block},e),this.props.navItem?this.renderNavItem(e):(t=this.props.href||this.props.target||this.props.navDropdown?"renderAnchor":"renderButton",this[t](e))},renderAnchor:function(e){var t=this.props.componentClass||"a",r=this.props.href||"#";return e.disabled=this.props.disabled,a["default"].createElement(t,o({},this.props,{href:r,className:l["default"](this.props.className,e),role:"button"}),this.props.children)},renderButton:function(e){var t=this.props.componentClass||"button";return a["default"].createElement(t,o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)},renderNavItem:function(e){var t={active:this.props.active};return a["default"].createElement("li",{className:l["default"](t)},this.renderAnchor(e))}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=e.querySelectorAll("."+t.join("."));r=[].map.call(r,function(e){return e});for(var n=0;n<t.length;n++)if(!e.className.match(new RegExp("\\b"+t[n]+"\\b")))return r;return r.unshift(e),r}Object.defineProperty(t,"__esModule",{value:!0});var s=r(1),a=n(s),i=r(5),l=n(i);t["default"]={_fadeIn:function(){var e=void 0;this.isMounted()&&(e=o(a["default"].findDOMNode(this),["fade"]),e.length&&e.forEach(function(e){e.className+=" in"}))},_fadeOut:function(){var e=o(this._fadeOutEl,["fade","in"]);e.length&&e.forEach(function(e){e.className=e.className.replace(/\bin\b/,"")}),setTimeout(this._handleFadeOutEnd,300)},_handleFadeOutEnd:function(){this._fadeOutEl&&this._fadeOutEl.parentNode&&this._fadeOutEl.parentNode.removeChild(this._fadeOutEl)},componentDidMount:function(){document.querySelectorAll&&setTimeout(this._fadeIn,20)},componentWillUnmount:function(){var e=o(a["default"].findDOMNode(this),["fade"]),t=this.props.container&&a["default"].findDOMNode(this.props.container)||l["default"].ownerDocument(this).body;e.length&&(this._fadeOutEl=document.createElement("div"),t.appendChild(this._fadeOutEl),this._fadeOutEl.appendChild(a["default"].findDOMNode(this).cloneNode(!0)),setTimeout(this._fadeOut,20))}},e.exports=t["default"]},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={CLASSES:{alert:"alert",button:"btn","button-group":"btn-group","button-toolbar":"btn-toolbar",column:"col","input-group":"input-group",form:"form",glyphicon:"glyphicon",label:"label",thumbnail:"thumbnail","list-group-item":"list-group-item",panel:"panel","panel-group":"panel-group","progress-bar":"progress-bar",nav:"nav",navbar:"navbar",modal:"modal",row:"row",well:"well"},STYLES:{"default":"default",primary:"primary",success:"success",info:"info",warning:"warning",danger:"danger",link:"link",inline:"inline",tabs:"tabs",pills:"pills"},addStyle:function(e){n.STYLES[e]=e},SIZES:{large:"lg",medium:"md",small:"sm",xsmall:"xs"},GLYPHS:["asterisk","plus","euro","eur","minus","cloud","envelope","pencil","glass","music","search","heart","star","star-empty","user","film","th-large","th","th-list","ok","remove","zoom-in","zoom-out","off","signal","cog","trash","home","file","time","road","download-alt","download","upload","inbox","play-circle","repeat","refresh","list-alt","lock","flag","headphones","volume-off","volume-down","volume-up","qrcode","barcode","tag","tags","book","bookmark","print","camera","font","bold","italic","text-height","text-width","align-left","align-center","align-right","align-justify","list","indent-left","indent-right","facetime-video","picture","map-marker","adjust","tint","edit","share","check","move","step-backward","fast-backward","backward","play","pause","stop","forward","fast-forward","step-forward","eject","chevron-left","chevron-right","plus-sign","minus-sign","remove-sign","ok-sign","question-sign","info-sign","screenshot","remove-circle","ok-circle","ban-circle","arrow-left","arrow-right","arrow-up","arrow-down","share-alt","resize-full","resize-small","exclamation-sign","gift","leaf","fire","eye-open","eye-close","warning-sign","plane","calendar","random","comment","magnet","chevron-up","chevron-down","retweet","shopping-cart","folder-close","folder-open","resize-vertical","resize-horizontal","hdd","bullhorn","bell","certificate","thumbs-up","thumbs-down","hand-right","hand-left","hand-up","hand-down","circle-arrow-right","circle-arrow-left","circle-arrow-up","circle-arrow-down","globe","wrench","tasks","filter","briefcase","fullscreen","dashboard","paperclip","heart-empty","link","phone","pushpin","usd","gbp","sort","sort-by-alphabet","sort-by-alphabet-alt","sort-by-order","sort-by-order-alt","sort-by-attributes","sort-by-attributes-alt","unchecked","expand","collapse-down","collapse-up","log-in","flash","log-out","new-window","record","save","open","saved","import","export","send","floppy-disk","floppy-saved","floppy-remove","floppy-save","floppy-open","credit-card","transfer","cutlery","header","compressed","earphone","phone-alt","tower","stats","sd-video","hd-video","subtitles","sound-stereo","sound-dolby","sound-5-1","sound-6-1","sound-7-1","copyright-mark","registration-mark","cloud-download","cloud-upload","tree-conifer","tree-deciduous","cd","save-file","open-file","level-up","copy","paste","alert","equalizer","king","queen","pawn","bishop","knight","baby-formula","tent","blackboard","bed","apple","erase","hourglass","lamp","duplicate","piggy-bank","scissors","bitcoin","yen","ruble","scale","ice-lolly","ice-lolly-tasted","education","option-horizontal","option-vertical","menu-hamburger","modal-window","oil","grain","sunglasses","text-size","text-color","text-background","object-align-top","object-align-bottom","object-align-horizontal","object-align-left","object-align-vertical","object-align-right","triangle-right","triangle-left","triangle-bottom","triangle-top","console","superscript","subscript","menu-left","menu-right","menu-down","menu-up"]};t["default"]=n,e.exports=t["default"]},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={listen:function(e,t,r){return e.addEventListener?(e.addEventListener(t,r,!1),{remove:function(){e.removeEventListener(t,r,!1)}}):e.attachEvent?(e.attachEvent("on"+t,r),{remove:function(){e.detachEvent("on"+t,r)}}):void 0}};t["default"]=n,e.exports=t["default"]},function(e,t,r){"use strict";function n(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var r=Object(e),n=Object.prototype.hasOwnProperty,o=1;o<arguments.length;o++){var s=arguments[o];if(null!=s){var a=Object(s);for(var i in a)n.call(a,i)&&(r[i]=a[i])}}return r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=a["default"].createClass({displayName:"ButtonGroup",mixins:[u["default"]],propTypes:{vertical:a["default"].PropTypes.bool,justified:a["default"].PropTypes.bool},getDefaultProps:function(){return{bsClass:"button-group"}},render:function(){var e=this.getBsClassSet();return e["btn-group"]=!this.props.vertical,e["btn-group-vertical"]=this.props.vertical,e["btn-group-justified"]=this.props.justified,a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(6),u=n(p),d=r(4),f=n(d),c=a["default"].createClass({displayName:"DropdownMenu",propTypes:{pullRight:a["default"].PropTypes.bool,onSelect:a["default"].PropTypes.func},render:function(){var e={"dropdown-menu":!0,"dropdown-menu-right":this.props.pullRight};return a["default"].createElement("ul",o({},this.props,{className:l["default"](this.props.className,e),role:"menu"}),f["default"].map(this.props.children,this.renderMenuItem))},renderMenuItem:function(e,t){return s.cloneElement(e,{onSelect:u["default"](e.props.onSelect,this.props.onSelect),key:e.key?e.key:t})}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(;e;){if(e===t)return!0;e=e.parentNode}return!1}Object.defineProperty(t,"__esModule",{value:!0});var s=r(1),a=n(s),i=r(5),l=n(i),p=r(12),u=n(p),d={getInitialState:function(){return{open:!1}},setDropdownState:function(e,t){e?this.bindRootCloseHandlers():this.unbindRootCloseHandlers(),this.setState({open:e},t)},handleDocumentKeyUp:function(e){27===e.keyCode&&this.setDropdownState(!1)},handleDocumentClick:function(e){o(e.target,a["default"].findDOMNode(this))||this.setDropdownState(!1)},bindRootCloseHandlers:function(){var e=l["default"].ownerDocument(this);this._onDocumentClickListener=u["default"].listen(e,"click",this.handleDocumentClick),this._onDocumentKeyupListener=u["default"].listen(e,"keyup",this.handleDocumentKeyUp)},unbindRootCloseHandlers:function(){this._onDocumentClickListener&&this._onDocumentClickListener.remove(),this._onDocumentKeyupListener&&this._onDocumentKeyupListener.remove()},componentWillUnmount:function(){this.unbindRootCloseHandlers()}};t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(29),i=n(a),l=r(5),p=n(l);t["default"]={propTypes:{container:i["default"].mountable},componentWillUnmount:function(){this._unrenderOverlay(),this._overlayTarget&&(this.getContainerDOMNode().removeChild(this._overlayTarget),this._overlayTarget=null)},componentDidUpdate:function(){this._renderOverlay()},componentDidMount:function(){this._renderOverlay()},_mountOverlayTarget:function(){this._overlayTarget=document.createElement("div"),this.getContainerDOMNode().appendChild(this._overlayTarget)},_renderOverlay:function(){this._overlayTarget||this._mountOverlayTarget();var e=this.renderOverlay();null!==e?this._overlayInstance=s["default"].render(e,this._overlayTarget):this._unrenderOverlay()},_unrenderOverlay:function(){s["default"].unmountComponentAtNode(this._overlayTarget),this._overlayInstance=null},getOverlayDOMNode:function(){if(!this.isMounted())throw new Error("getOverlayDOMNode(): A component must be mounted to have a DOM node.");return this._overlayInstance?s["default"].findDOMNode(this._overlayInstance):null},getContainerDOMNode:function(){return s["default"].findDOMNode(this.props.container)||p["default"].ownerDocument(this).body}},e.exports=t["default"]},function(e,t,r){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete i.animationend.animation,"TransitionEvent"in window||delete i.transitionend.transition;for(var r in i){var n=i[r];for(var o in n)if(o in t){l.push(n[o]);break}}}function o(e,t,r){e.addEventListener(t,r,!1)}function s(e,t,r){e.removeEventListener(t,r,!1)}Object.defineProperty(t,"__esModule",{value:!0});var a=!("undefined"==typeof window||!window.document||!window.document.createElement),i={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},l=[];a&&n();var p={addEndEventListener:function(e,t){return 0===l.length?void window.setTimeout(t,0):void l.forEach(function(r){o(e,r,t)})},removeEndEventListener:function(e,t){0!==l.length&&l.forEach(function(r){s(e,r,t)})}};t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return void 0!==e[t]&&l["default"](""+t+" in "+r,"collapsible","https://github.com/react-bootstrap/react-bootstrap/issues/425"),a["default"].PropTypes.bool.call(null,e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var s=r(1),a=n(s),i=r(8),l=n(i);e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(5),i=n(a),l=r(12),p=n(l),u={propTypes:{offset:s["default"].PropTypes.number,offsetTop:s["default"].PropTypes.number,offsetBottom:s["default"].PropTypes.number},getInitialState:function(){return{affixClass:"affix-top"}},getPinnedOffset:function(e){return this.pinnedOffset?this.pinnedOffset:(e.className=e.className.replace(/affix-top|affix-bottom|affix/,""),e.className+=e.className.length?" affix":"affix",this.pinnedOffset=i["default"].getOffset(e).top-window.pageYOffset,this.pinnedOffset)},checkPosition:function(){var e=void 0,t=void 0,r=void 0,n=void 0,o=void 0,a=void 0,l=void 0,p=void 0,u=void 0;this.isMounted()&&(e=s["default"].findDOMNode(this),t=document.documentElement.offsetHeight,r=window.pageYOffset,n=i["default"].getOffset(e),"top"===this.affixed&&(n.top+=r),o=null!=this.props.offsetTop?this.props.offsetTop:this.props.offset,a=null!=this.props.offsetBottom?this.props.offsetBottom:this.props.offset,(null!=o||null!=a)&&(null==o&&(o=0),null==a&&(a=0),l=null!=this.unpin&&r+this.unpin<=n.top?!1:null!=a&&n.top+e.offsetHeight>=t-a?"bottom":null!=o&&o>=r?"top":!1,this.affixed!==l&&(null!=this.unpin&&(e.style.top=""),p="affix"+(l?"-"+l:""),this.affixed=l,this.unpin="bottom"===l?this.getPinnedOffset(e):null,"bottom"===l&&(e.className=e.className.replace(/affix-top|affix-bottom|affix/,"affix-bottom"),u=t-a-e.offsetHeight-i["default"].getOffset(e).top),this.setState({affixClass:p,affixPositionTop:u}))))},checkPositionWithEventLoop:function(){setTimeout(this.checkPosition,0)},componentDidMount:function(){this._onWindowScrollListener=p["default"].listen(window,"scroll",this.checkPosition),this._onDocumentClickListener=p["default"].listen(i["default"].ownerDocument(this),"click",this.checkPositionWithEventLoop)},componentWillUnmount:function(){this._onWindowScrollListener&&this._onWindowScrollListener.remove(),this._onDocumentClickListener&&this._onDocumentClickListener.remove()},componentDidUpdate:function(e,t){t.affixClass===this.state.affixClass&&this.checkPositionWithEventLoop()}};t["default"]=u,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}function i(e,t,r){var n=e.children,o=e.value;return n&&o?new Error("Both value and children cannot be passed to ButtonInput"):d["default"].PropTypes.oneOfType([d["default"].PropTypes.string,d["default"].PropTypes.number]).call(null,{children:n,value:o},t,r)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},p=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),u=r(1),d=n(u),f=r(9),c=n(f),h=r(23),m=n(h),v=r(24),y=n(v),b=function(e){function t(){s(this,t),null!=e&&e.apply(this,arguments)}return a(t,e),p(t,[{key:"renderFormGroup",value:function(e){var t=this.props,r=(t.bsStyle,t.value,o(t,["bsStyle","value"]));return d["default"].createElement(m["default"],r,e)}},{key:"renderInput",value:function(){var e=this.props,t=e.children,r=e.value,n=o(e,["children","value"]),s=t?t:r;return d["default"].createElement(c["default"],l({},n,{componentClass:"input",ref:"input",key:"input",value:s}))}}]),t}(y["default"]);b.defaultProps={type:"button"},b.propTypes={type:d["default"].PropTypes.oneOf(["button","reset","submit"]),bsStyle:function(e){return null},children:i,value:i},t["default"]=b,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(3),i=n(a),l=r(7),p=n(l),u=r(2),d=n(u),f=r(5),c=n(f),h=r(19),m=n(h),v=r(4),y=n(v),b=r(6),g=n(b),P={mixins:[i["default"],p["default"]],propTypes:{onSelect:s["default"].PropTypes.func,activeHref:s["default"].PropTypes.string,activeKey:s["default"].PropTypes.any,collapsable:m["default"],collapsible:s["default"].PropTypes.bool,expanded:s["default"].PropTypes.bool,eventKey:s["default"].PropTypes.any},getCollapsibleDOMNode:function(){return s["default"].findDOMNode(this)},getCollapsibleDimensionValue:function(){var e=0,t=this.refs;for(var r in t)if(t.hasOwnProperty(r)){var n=s["default"].findDOMNode(t[r]),o=n.offsetHeight,a=c["default"].getComputedStyles(n);e+=o+parseInt(a.marginTop,10)+parseInt(a.marginBottom,10)}return e},render:function(){var e=this.props.collapsible||this.props.collapsable,t=e?this.getCollapsibleClassSet():{};return(void 0===this.props.className||-2===this.props.className.split(" ").indexOf("navbar-collapse"))&&(t["navbar-collapse"]=e),s["default"].createElement("div",{eventKey:this.props.eventKey,className:d["default"](this.props.className,t)},y["default"].map(this.props.children,e?this.renderCollapsibleNavChildren:this.renderChildren))},getChildActiveProp:function(e){return e.props.active?!0:null!=this.props.activeKey&&e.props.eventKey===this.props.activeKey?!0:null!=this.props.activeHref&&e.props.href===this.props.activeHref?!0:e.props.active},renderChildren:function(e,t){var r=e.key?e.key:t;return o.cloneElement(e,{activeKey:this.props.activeKey,activeHref:this.props.activeHref,ref:"nocollapse_"+r,key:r,navItem:!0})},renderCollapsibleNavChildren:function(e,t){var r=e.key?e.key:t;return o.cloneElement(e,{active:this.getChildActiveProp(e),activeKey:this.props.activeKey,activeHref:this.props.activeHref,onSelect:g["default"](e.props.onSelect,this.props.onSelect),ref:"collapsible_"+r,key:r,navItem:!0})}},O=s["default"].createClass(P);t.specCollapsibleNav=P,t["default"]=O},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(1),l=n(i),p=r(2),u=n(p),d=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return s(t,e),a(t,[{key:"render",value:function(){var e={"form-group":!this.props.standalone,"form-group-lg":!this.props.standalone&&"large"===this.props.bsSize,"form-group-sm":!this.props.standalone&&"small"===this.props.bsSize,"has-feedback":this.props.hasFeedback,"has-success":"success"===this.props.bsStyle,"has-warning":"warning"===this.props.bsStyle,"has-error":"error"===this.props.bsStyle};return l["default"].createElement("div",{className:u["default"](e,this.props.groupClassName)},this.props.children)}}]),t}(l["default"].Component);d.defaultProps={standalone:!1},d.propTypes={standalone:l["default"].PropTypes.bool,hasFeedback:l["default"].PropTypes.bool,bsSize:function(e){return e.standalone&&void 0!==e.bsSize?new Error("bsSize will not be used when `standalone` is set."):l["default"].PropTypes.oneOf(["small","medium","large"]).apply(null,arguments)},bsStyle:l["default"].PropTypes.oneOf(["success","warning","error"]),groupClassName:l["default"].PropTypes.string},t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(1),p=n(l),u=r(2),d=n(u),f=r(23),c=n(f),h=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return s(t,e),i(t,[{key:"getInputDOMNode",value:function(){return p["default"].findDOMNode(this.refs.input)}},{key:"getValue",value:function(){if("static"===this.props.type)return this.props.value;if(this.props.type)return"select"===this.props.type&&this.props.multiple?this.getSelectedOptions():this.getInputDOMNode().value;throw"Cannot use getValue without specifying input type."}},{key:"getChecked",value:function(){return this.getInputDOMNode().checked}},{key:"getSelectedOptions",value:function(){var e=[];return Array.prototype.forEach.call(this.getInputDOMNode().getElementsByTagName("option"),function(t){if(t.selected){var r=t.getAttribute("value")||t.innerHtml;e.push(r)}}),e}},{key:"isCheckboxOrRadio",value:function(){return"checkbox"===this.props.type||"radio"===this.props.type}},{key:"isFile",value:function(){return"file"===this.props.type}},{key:"renderInputGroup",value:function(e){var t=this.props.addonBefore?p["default"].createElement("span",{className:"input-group-addon",key:"addonBefore"},this.props.addonBefore):null,r=this.props.addonAfter?p["default"].createElement("span",{className:"input-group-addon",key:"addonAfter"},this.props.addonAfter):null,n=this.props.buttonBefore?p["default"].createElement("span",{className:"input-group-btn"},this.props.buttonBefore):null,o=this.props.buttonAfter?p["default"].createElement("span",{className:"input-group-btn"},this.props.buttonAfter):null,s=void 0;switch(this.props.bsSize){case"small":s="input-group-sm";break;case"large":s="input-group-lg"}return t||r||n||o?p["default"].createElement("div",{className:d["default"](s,"input-group"),key:"input-group"},t,n,e,r,o):e}},{key:"renderIcon",value:function(){var e={glyphicon:!0,"form-control-feedback":!0,"glyphicon-ok":"success"===this.props.bsStyle,"glyphicon-warning-sign":"warning"===this.props.bsStyle,"glyphicon-remove":"error"===this.props.bsStyle};return this.props.hasFeedback?p["default"].createElement("span",{className:d["default"](e),key:"icon"}):null}},{key:"renderHelp",value:function(){return this.props.help?p["default"].createElement("span",{className:"help-block",key:"help"},this.props.help):null}},{key:"renderCheckboxAndRadioWrapper",value:function(e){var t={checkbox:"checkbox"===this.props.type,radio:"radio"===this.props.type};return p["default"].createElement("div",{className:d["default"](t),key:"checkboxRadioWrapper"},e)}},{key:"renderWrapper",value:function(e){return this.props.wrapperClassName?p["default"].createElement("div",{className:this.props.wrapperClassName,key:"wrapper"},e):e}},{key:"renderLabel",value:function(e){var t={"control-label":!this.isCheckboxOrRadio()};return t[this.props.labelClassName]=this.props.labelClassName,this.props.label?p["default"].createElement("label",{htmlFor:this.props.id,className:d["default"](t),key:"label"},e,this.props.label):e}},{key:"renderInput",value:function(){if(!this.props.type)return this.props.children;switch(this.props.type){case"select":return p["default"].createElement("select",a({},this.props,{className:d["default"](this.props.className,"form-control"),ref:"input",key:"input"}),this.props.children);case"textarea":return p["default"].createElement("textarea",a({},this.props,{className:d["default"](this.props.className,"form-control"),ref:"input",key:"input"}));case"static":return p["default"].createElement("p",a({},this.props,{ className:d["default"](this.props.className,"form-control-static"),ref:"input",key:"input"}),this.props.value)}var e=this.isCheckboxOrRadio()||this.isFile()?"":"form-control";return p["default"].createElement("input",a({},this.props,{className:d["default"](this.props.className,e),ref:"input",key:"input"}))}},{key:"renderFormGroup",value:function(e){return p["default"].createElement(c["default"],this.props,e)}},{key:"renderChildren",value:function(){return this.isCheckboxOrRadio()?this.renderWrapper([this.renderCheckboxAndRadioWrapper(this.renderLabel(this.renderInput())),this.renderHelp()]):[this.renderLabel(),this.renderWrapper([this.renderInputGroup(this.renderInput()),this.renderIcon(),this.renderHelp()])]}},{key:"render",value:function(){var e=this.renderChildren();return this.renderFormGroup(e)}}]),t}(p["default"].Component);h.propTypes={type:p["default"].PropTypes.string,label:p["default"].PropTypes.node,help:p["default"].PropTypes.node,addonBefore:p["default"].PropTypes.node,addonAfter:p["default"].PropTypes.node,buttonBefore:p["default"].PropTypes.node,buttonAfter:p["default"].PropTypes.node,bsSize:p["default"].PropTypes.oneOf(["small","medium","large"]),bsStyle:p["default"].PropTypes.oneOf(["success","warning","error"]),hasFeedback:p["default"].PropTypes.bool,id:p["default"].PropTypes.string,groupClassName:p["default"].PropTypes.string,wrapperClassName:p["default"].PropTypes.string,labelClassName:p["default"].PropTypes.string,multiple:p["default"].PropTypes.bool,disabled:p["default"].PropTypes.bool,value:p["default"].PropTypes.any},t["default"]=h,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(4),i=n(a),l=r(13),p=n(l),u=/\%\((.+?)\)s/,d=s["default"].createClass({displayName:"Interpolate",propTypes:{format:s["default"].PropTypes.string},getDefaultProps:function(){return{component:"span"}},render:function(){var e=i["default"].hasValidComponent(this.props.children)||"string"==typeof this.props.children?this.props.children:this.props.format,t=this.props.component,r=this.props.unsafe===!0,n=p["default"]({},this.props);if(delete n.children,delete n.format,delete n.component,delete n.unsafe,r){var o=e.split(u).reduce(function(e,t,r){var o=void 0;if(r%2===0?o=t:(o=n[t],delete n[t]),s["default"].isValidElement(o))throw new Error("cannot interpolate a React component into unsafe text");return e+=o},"");return n.dangerouslySetInnerHTML={__html:o},s["default"].createElement(t,n)}var a=e.split(u).reduce(function(e,t,r){var o=void 0;if(r%2===0){if(0===t.length)return e;o=t}else o=n[t],delete n[t];return e.push(o),e},[]);return s["default"].createElement(t,n,a)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(3),l=n(i),p=r(7),u=n(p),d=r(2),f=n(d),c=r(5),h=n(c),m=r(19),v=n(m),y=r(4),b=n(y),g=r(6),P=n(g),O=a["default"].createClass({displayName:"Nav",mixins:[l["default"],u["default"]],propTypes:{activeHref:a["default"].PropTypes.string,activeKey:a["default"].PropTypes.any,bsStyle:a["default"].PropTypes.oneOf(["tabs","pills"]),stacked:a["default"].PropTypes.bool,justified:a["default"].PropTypes.bool,onSelect:a["default"].PropTypes.func,collapsable:v["default"],collapsible:a["default"].PropTypes.bool,expanded:a["default"].PropTypes.bool,navbar:a["default"].PropTypes.bool,eventKey:a["default"].PropTypes.any,pullRight:a["default"].PropTypes.bool,right:a["default"].PropTypes.bool},getDefaultProps:function(){return{bsClass:"nav"}},getCollapsibleDOMNode:function(){return a["default"].findDOMNode(this)},getCollapsibleDimensionValue:function(){var e=a["default"].findDOMNode(this.refs.ul),t=e.offsetHeight,r=h["default"].getComputedStyles(e);return t+parseInt(r.marginTop,10)+parseInt(r.marginBottom,10)},render:function(){var e=this.props.collapsible||this.props.collapsable,t=e?this.getCollapsibleClassSet():{};return t["navbar-collapse"]=e,this.props.navbar&&!e?this.renderUl():a["default"].createElement("nav",o({},this.props,{className:f["default"](this.props.className,t)}),this.renderUl())},renderUl:function(){var e=this.getBsClassSet();return e["nav-stacked"]=this.props.stacked,e["nav-justified"]=this.props.justified,e["navbar-nav"]=this.props.navbar,e["pull-right"]=this.props.pullRight,e["navbar-right"]=this.props.right,a["default"].createElement("ul",o({},this.props,{className:f["default"](this.props.className,e),ref:"ul"}),b["default"].map(this.props.children,this.renderNavItem))},getChildActiveProp:function(e){return e.props.active?!0:null!=this.props.activeKey&&e.props.eventKey===this.props.activeKey?!0:null!=this.props.activeHref&&e.props.href===this.props.activeHref?!0:e.props.active},renderNavItem:function(e,t){return s.cloneElement(e,{active:this.getChildActiveProp(e),activeKey:this.props.activeKey,activeHref:this.props.activeHref,onSelect:P["default"](e.props.onSelect,this.props.onSelect),key:e.key?e.key:t,navItem:!0})}});t["default"]=O,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(1),i=n(a),l=r(2),p=n(l),u=r(3),d=n(u),f=i["default"].createClass({displayName:"NavItem",mixins:[d["default"]],propTypes:{onSelect:i["default"].PropTypes.func,active:i["default"].PropTypes.bool,disabled:i["default"].PropTypes.bool,href:i["default"].PropTypes.string,title:i["default"].PropTypes.node,eventKey:i["default"].PropTypes.any,target:i["default"].PropTypes.string},getDefaultProps:function(){return{href:"#"}},render:function(){var e=this.props,t=e.disabled,r=e.active,n=e.href,a=e.title,l=e.target,u=e.children,d=o(e,["disabled","active","href","title","target","children"]),f={active:r,disabled:t},c={href:n,title:a,target:l,onClick:this.handleClick,ref:"anchor"};return"#"===n&&(c.role="button"),i["default"].createElement("li",s({},d,{className:p["default"](d.className,f)}),i["default"].createElement("a",c,u))},handleClick:function(e){this.props.onSelect&&(e.preventDefault(),this.props.disabled||this.props.onSelect(this.props.eventKey,this.props.href,this.props.target))}});t["default"]=f,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=r(4),f=n(d),c=a["default"].createClass({displayName:"PanelGroup",mixins:[u["default"]],propTypes:{accordion:a["default"].PropTypes.bool,activeKey:a["default"].PropTypes.any,defaultActiveKey:a["default"].PropTypes.any,onSelect:a["default"].PropTypes.func},getDefaultProps:function(){return{bsClass:"panel-group"}},getInitialState:function(){var e=this.props.defaultActiveKey;return{activeKey:e}},render:function(){var e=this.getBsClassSet();return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e),onSelect:null}),f["default"].map(this.props.children,this.renderPanel))},renderPanel:function(e,t){var r=null!=this.props.activeKey?this.props.activeKey:this.state.activeKey,n={bsStyle:e.props.bsStyle||this.props.bsStyle,key:e.key?e.key:t,ref:e.ref};return this.props.accordion&&(n.collapsible=!0,n.expanded=e.props.eventKey===r,n.onSelect=this.handleSelect),s.cloneElement(e,n)},shouldComponentUpdate:function(){return!this._isChanging},handleSelect:function(e,t){e.preventDefault(),this.props.onSelect&&(this._isChanging=!0,this.props.onSelect(t),this._isChanging=!1),this.state.activeKey===t&&(t=null),this.setState({activeKey:t})}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){function t(t,r,n,o){return o=o||a,null!=r[n]?e(r,n,o):t?new Error("Required prop `"+n+"` was not specified in `"+o+"`."):void 0}var r=t.bind(null,!1);return r.isRequired=t.bind(null,!0),r}function o(){function e(e,t,r){return"object"!=typeof e[t]||"function"!=typeof e[t].render&&1!==e[t].nodeType?new Error("Invalid prop `"+t+"` supplied to `"+r+"`, expected a DOM element or an object that has a `render` method"):void 0}return n(e)}function s(e){function t(t,r,n){var o=t[r];if(!e.hasOwnProperty(o)){var s=JSON.stringify(Object.keys(e));return new Error("Invalid prop '"+r+"' of value '"+o+"' "+("supplied to '"+n+"', expected one of "+s+"."))}}return n(t)}Object.defineProperty(t,"__esModule",{value:!0});var a="<<anonymous>>",i={mountable:o(),keyOf:s};t["default"]=i,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}function i(e,t){return function(r){var n=function(e){function t(){s(this,t),null!=e&&e.apply(this,arguments)}return a(t,e),p(t,[{key:"getChildContext",value:function(){return this.props.context}},{key:"render",value:function(){var e=this.props,t=e.wrapped,r=o(e,["wrapped"]);return delete r.context,d["default"].cloneElement(t,r)}}]),t}(d["default"].Component);n.childContextTypes=r;var i=function(){function r(){s(this,r)}return p(r,[{key:"render",value:function(){var r=l({},this.props);return r[t]=this.getWrappedOverlay(),d["default"].createElement(e,r,this.props.children)}},{key:"getWrappedOverlay",value:function(){return d["default"].createElement(n,{context:this.context,wrapped:this.props[t]})}}]),r}();return i.contextTypes=r,i}}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},p=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}();t["default"]=i;var u=r(1),d=n(u);e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(28),l=n(i),p=a["default"].createClass({displayName:"Accordion",render:function(){return a["default"].createElement(l["default"],o({},this.props,{accordion:!0}),this.props.children)}});t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(20),u=n(p),d=r(5),f=n(d),c=a["default"].createClass({displayName:"Affix",statics:{domUtils:f["default"]},mixins:[u["default"]],render:function(){var e={top:this.state.affixPositionTop};return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,this.state.affixClass),style:e}),this.props.children)}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=a["default"].createClass({displayName:"Alert",mixins:[u["default"]],propTypes:{onDismiss:a["default"].PropTypes.func,dismissAfter:a["default"].PropTypes.number},getDefaultProps:function(){return{bsClass:"alert",bsStyle:"info"}},renderDismissButton:function(){return a["default"].createElement("button",{type:"button",className:"close",onClick:this.props.onDismiss,"aria-hidden":"true"},"×")},render:function(){var e=this.getBsClassSet(),t=!!this.props.onDismiss;return e["alert-dismissable"]=t,a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),t?this.renderDismissButton():null,this.props.children)},componentDidMount:function(){this.props.dismissAfter&&this.props.onDismiss&&(this.dismissTimer=setTimeout(this.props.onDismiss,this.props.dismissAfter))},componentWillUnmount:function(){clearTimeout(this.dismissTimer)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(4),l=n(i),p=r(2),u=n(p),d=a["default"].createClass({displayName:"Badge",propTypes:{pullRight:a["default"].PropTypes.bool},hasContent:function(){return l["default"].hasValidComponent(this.props.children)||a["default"].Children.count(this.props.children)>1||"string"==typeof this.props.children||"number"==typeof this.props.children},render:function(){var e={"pull-right":this.props.pullRight,badge:this.hasContent()};return a["default"].createElement("span",o({},this.props,{className:u["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=a["default"].createClass({displayName:"ButtonToolbar",mixins:[u["default"]],getDefaultProps:function(){return{bsClass:"button-toolbar"}},render:function(){var e=this.getBsClassSet();return a["default"].createElement("div",o({},this.props,{role:"toolbar",className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=r(4),f=n(d),c=a["default"].createClass({displayName:"Carousel",mixins:[u["default"]],propTypes:{slide:a["default"].PropTypes.bool,indicators:a["default"].PropTypes.bool,interval:a["default"].PropTypes.number,controls:a["default"].PropTypes.bool,pauseOnHover:a["default"].PropTypes.bool,wrap:a["default"].PropTypes.bool,onSelect:a["default"].PropTypes.func,onSlideEnd:a["default"].PropTypes.func,activeIndex:a["default"].PropTypes.number,defaultActiveIndex:a["default"].PropTypes.number,direction:a["default"].PropTypes.oneOf(["prev","next"])},getDefaultProps:function(){return{slide:!0,interval:5e3,pauseOnHover:!0,wrap:!0,indicators:!0,controls:!0}},getInitialState:function(){return{activeIndex:null==this.props.defaultActiveIndex?0:this.props.defaultActiveIndex,previousActiveIndex:null,direction:null}},getDirection:function(e,t){return e===t?null:e>t?"prev":"next"},componentWillReceiveProps:function(e){var t=this.getActiveIndex();null!=e.activeIndex&&e.activeIndex!==t&&(clearTimeout(this.timeout),this.setState({previousActiveIndex:t,direction:null!=e.direction?e.direction:this.getDirection(t,e.activeIndex)}))},componentDidMount:function(){this.waitForNext()},componentWillUnmount:function(){clearTimeout(this.timeout)},next:function(e){e&&e.preventDefault();var t=this.getActiveIndex()+1,r=f["default"].numberOf(this.props.children);if(t>r-1){if(!this.props.wrap)return;t=0}this.handleSelect(t,"next")},prev:function(e){e&&e.preventDefault();var t=this.getActiveIndex()-1;if(0>t){if(!this.props.wrap)return;t=f["default"].numberOf(this.props.children)-1}this.handleSelect(t,"prev")},pause:function(){this.isPaused=!0,clearTimeout(this.timeout)},play:function(){this.isPaused=!1,this.waitForNext()},waitForNext:function(){!this.isPaused&&this.props.slide&&this.props.interval&&null==this.props.activeIndex&&(this.timeout=setTimeout(this.next,this.props.interval))},handleMouseOver:function(){this.props.pauseOnHover&&this.pause()},handleMouseOut:function(){this.isPaused&&this.play()},render:function(){var e={carousel:!0,slide:this.props.slide};return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e),onMouseOver:this.handleMouseOver,onMouseOut:this.handleMouseOut}),this.props.indicators?this.renderIndicators():null,a["default"].createElement("div",{className:"carousel-inner",ref:"inner"},f["default"].map(this.props.children,this.renderItem)),this.props.controls?this.renderControls():null)},renderPrev:function(){return a["default"].createElement("a",{className:"left carousel-control",href:"#prev",key:0,onClick:this.prev},a["default"].createElement("span",{className:"glyphicon glyphicon-chevron-left"}))},renderNext:function(){return a["default"].createElement("a",{className:"right carousel-control",href:"#next",key:1,onClick:this.next},a["default"].createElement("span",{className:"glyphicon glyphicon-chevron-right"}))},renderControls:function(){if(!this.props.wrap){var e=this.getActiveIndex(),t=f["default"].numberOf(this.props.children);return[0!==e?this.renderPrev():null,e!==t-1?this.renderNext():null]}return[this.renderPrev(),this.renderNext()]},renderIndicator:function(e,t){var r=t===this.getActiveIndex()?"active":null;return a["default"].createElement("li",{key:t,className:r,onClick:this.handleSelect.bind(this,t,null)})},renderIndicators:function(){var e=[];return f["default"].forEach(this.props.children,function(t,r){e.push(this.renderIndicator(t,r)," ")},this),a["default"].createElement("ol",{className:"carousel-indicators"},e)},getActiveIndex:function(){return null!=this.props.activeIndex?this.props.activeIndex:this.state.activeIndex},handleItemAnimateOutEnd:function(){this.setState({previousActiveIndex:null,direction:null},function(){this.waitForNext(),this.props.onSlideEnd&&this.props.onSlideEnd()})},renderItem:function(e,t){var r=this.getActiveIndex(),n=t===r,o=null!=this.state.previousActiveIndex&&this.state.previousActiveIndex===t&&this.props.slide;return s.cloneElement(e,{active:n,ref:e.ref,key:e.key?e.key:t,index:t,animateOut:o,animateIn:n&&null!=this.state.previousActiveIndex&&this.props.slide,direction:this.state.direction,onAnimateOutEnd:o?this.handleItemAnimateOutEnd:null})},handleSelect:function(e,t){clearTimeout(this.timeout);var r=this.getActiveIndex();if(t=t||this.getDirection(r,e),this.props.onSelect&&this.props.onSelect(e,t),null==this.props.activeIndex&&e!==r){if(null!=this.state.previousActiveIndex)return;this.setState({activeIndex:e,previousActiveIndex:r,direction:t})}}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(18),u=n(p),d=a["default"].createClass({displayName:"CarouselItem",propTypes:{direction:a["default"].PropTypes.oneOf(["prev","next"]),onAnimateOutEnd:a["default"].PropTypes.func,active:a["default"].PropTypes.bool,animateIn:a["default"].PropTypes.bool,animateOut:a["default"].PropTypes.bool,caption:a["default"].PropTypes.node,index:a["default"].PropTypes.number},getInitialState:function(){return{direction:null}},getDefaultProps:function(){return{animation:!0}},handleAnimateOutEnd:function(){this.props.onAnimateOutEnd&&this.isMounted()&&this.props.onAnimateOutEnd(this.props.index)},componentWillReceiveProps:function(e){this.props.active!==e.active&&this.setState({direction:null})},componentDidUpdate:function(e){!this.props.active&&e.active&&u["default"].addEndEventListener(a["default"].findDOMNode(this),this.handleAnimateOutEnd),this.props.active!==e.active&&setTimeout(this.startAnimation,20)},startAnimation:function(){this.isMounted()&&this.setState({direction:"prev"===this.props.direction?"right":"left"})},render:function(){var e={item:!0,active:this.props.active&&!this.props.animateIn||this.props.animateOut,next:this.props.active&&this.props.animateIn&&"next"===this.props.direction,prev:this.props.active&&this.props.animateIn&&"prev"===this.props.direction};return this.state.direction&&(this.props.animateIn||this.props.animateOut)&&(e[this.state.direction]=!0),a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children,this.props.caption?this.renderCaption():null)},renderCaption:function(){return a["default"].createElement("div",{className:"carousel-caption"},this.props.caption)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(11),u=n(p),d=a["default"].createClass({displayName:"Col",propTypes:{xs:a["default"].PropTypes.number,sm:a["default"].PropTypes.number,md:a["default"].PropTypes.number,lg:a["default"].PropTypes.number,xsOffset:a["default"].PropTypes.number,smOffset:a["default"].PropTypes.number,mdOffset:a["default"].PropTypes.number,lgOffset:a["default"].PropTypes.number,xsPush:a["default"].PropTypes.number,smPush:a["default"].PropTypes.number,mdPush:a["default"].PropTypes.number,lgPush:a["default"].PropTypes.number,xsPull:a["default"].PropTypes.number,smPull:a["default"].PropTypes.number,mdPull:a["default"].PropTypes.number,lgPull:a["default"].PropTypes.number,componentClass:a["default"].PropTypes.node.isRequired},getDefaultProps:function(){return{componentClass:"div"}},render:function(){var e=this.props.componentClass,t={};return Object.keys(u["default"].SIZES).forEach(function(e){var r=u["default"].SIZES[e],n=r,o=r+"-";this.props[n]&&(t["col-"+o+this.props[n]]=!0),n=r+"Offset",o=r+"-offset-",this.props[n]>=0&&(t["col-"+o+this.props[n]]=!0),n=r+"Push",o=r+"-push-",this.props[n]>=0&&(t["col-"+o+this.props[n]]=!0),n=r+"Pull",o=r+"-pull-",this.props[n]>=0&&(t["col-"+o+this.props[n]]=!0)},this),a["default"].createElement(e,o({},this.props,{className:l["default"](this.props.className,t)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(13),s=n(o),a=r(8),i=n(a),l=r(7),p=n(l),u="https://github.com/react-bootstrap/react-bootstrap/issues/425#issuecomment-97110963",d=s["default"]({},p["default"],{getCollapsableClassSet:function(e){return i["default"]("CollapsableMixin.getCollapsableClassSet()","CollapsibleMixin.getCollapsibleClassSet()",u),p["default"].getCollapsibleClassSet.call(this,e)},getCollapsibleDOMNode:function(){return i["default"]("CollapsableMixin.getCollapsableDOMNode()","CollapsibleMixin.getCollapsibleDOMNode()",u),this.getCollapsableDOMNode()},getCollapsibleDimensionValue:function(){return i["default"]("CollapsableMixin.getCollapsableDimensionValue()","CollapsibleMixin.getCollapsibleDimensionValue()",u),this.getCollapsableDimensionValue()},componentDidMount:function(){i["default"]("CollapsableMixin","CollapsibleMixin",u)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(8),i=n(a),l=r(13),p=n(l),u=r(22),d=p["default"]({},u.specCollapsibleNav,{componentDidMount:function(){i["default"]("CollapsableNav","CollapsibleNav","https://github.com/react-bootstrap/react-bootstrap/issues/425#issuecomment-97110963")}}),f=s["default"].createClass(d);t["default"]=f,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(6),u=n(p),d=r(3),f=n(d),c=r(16),h=n(c),m=r(9),v=n(m),y=r(14),b=n(y),g=r(15),P=n(g),O=r(4),T=n(O),C=a["default"].createClass({displayName:"DropdownButton",mixins:[f["default"],h["default"]],propTypes:{pullRight:a["default"].PropTypes.bool,dropup:a["default"].PropTypes.bool,title:a["default"].PropTypes.node,href:a["default"].PropTypes.string,onClick:a["default"].PropTypes.func,onSelect:a["default"].PropTypes.func,navItem:a["default"].PropTypes.bool,noCaret:a["default"].PropTypes.bool,buttonClassName:a["default"].PropTypes.string},render:function(){var e=this.props.navItem?"renderNavItem":"renderButtonGroup",t=this.props.noCaret?null:a["default"].createElement("span",{className:"caret"});return this[e]([a["default"].createElement(v["default"],o({},this.props,{ref:"dropdownButton",className:l["default"]("dropdown-toggle",this.props.buttonClassName),onClick:u["default"](this.props.onClick,this.handleDropdownClick),key:0,navDropdown:this.props.navItem,navItem:null,title:null,pullRight:null,dropup:null}),this.props.title," ",t),a["default"].createElement(P["default"],{ref:"menu","aria-labelledby":this.props.id,pullRight:this.props.pullRight,key:1},T["default"].map(this.props.children,this.renderMenuItem))])},renderButtonGroup:function(e){var t={open:this.state.open,dropup:this.props.dropup};return a["default"].createElement(b["default"],{bsSize:this.props.bsSize,className:l["default"](this.props.className,t)},e)},renderNavItem:function(e){var t={dropdown:!0,open:this.state.open,dropup:this.props.dropup};return a["default"].createElement("li",{className:l["default"](this.props.className,t)},e)},renderMenuItem:function(e,t){var r=this.props.onSelect||e.props.onSelect?this.handleOptionSelect:null;return s.cloneElement(e,{onSelect:u["default"](e.props.onSelect,r),key:e.key?e.key:t})},handleDropdownClick:function(e){e.preventDefault(),this.setDropdownState(!this.state.open)},handleOptionSelect:function(e){this.props.onSelect&&this.props.onSelect(e),this.setDropdownState(!1)}});t["default"]=C,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=r(11),f=n(d),c=a["default"].createClass({displayName:"Glyphicon",mixins:[u["default"]],propTypes:{glyph:a["default"].PropTypes.oneOf(f["default"].GLYPHS).isRequired},getDefaultProps:function(){return{bsClass:"glyphicon"}},render:function(){var e=this.getBsClassSet();return e["glyphicon-"+this.props.glyph]=!0,a["default"].createElement("span",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=a["default"].createClass({displayName:"Grid",propTypes:{fluid:a["default"].PropTypes.bool,componentClass:a["default"].PropTypes.node.isRequired},getDefaultProps:function(){return{componentClass:"div"}},render:function(){var e=this.props.componentClass,t=this.props.fluid?"container-fluid":"container";return a["default"].createElement(e,o({},this.props,{className:l["default"](this.props.className,t)}),this.props.children)}});t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=function(e,t,r){for(var n=!0;n;){var o=e,s=t,a=r;i=p=l=void 0,n=!1;var i=Object.getOwnPropertyDescriptor(o,s);if(void 0!==i){if("value"in i)return i.value;var l=i.get;return void 0===l?void 0:l.call(a)}var p=Object.getPrototypeOf(o);if(null===p)return void 0;e=p,t=s,r=a,n=!0}},l=r(1),p=n(l),u=r(24),d=n(u),f=r(21),c=n(f),h=r(8),m=n(h),v=["button","reset","submit"],y=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return s(t,e),a(t,[{key:"render",value:function(){return v.indexOf(this.props.type)>-1?(m["default"]("Input type="+this.props.type,"ButtonInput"),p["default"].createElement(c["default"],this.props)):i(Object.getPrototypeOf(t.prototype),"render",this).call(this)}}]),t}(d["default"]);t["default"]=y,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=a["default"].createClass({displayName:"Jumbotron",render:function(){return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,"jumbotron")}),this.props.children)}});t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=a["default"].createClass({displayName:"Label",mixins:[u["default"]],getDefaultProps:function(){return{bsClass:"label",bsStyle:"default"}},render:function(){var e=this.getBsClassSet();return a["default"].createElement("span",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function"); }function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(1),p=n(l),u=r(2),d=n(u),f=r(4),c=n(f),h=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return s(t,e),i(t,[{key:"render",value:function(){var e=this,t=c["default"].map(this.props.children,function(e,t){return l.cloneElement(e,{key:e.key?e.key:t})}),r=!1;if(!this.props.children)return this.renderDiv(t);if(1!==p["default"].Children.count(this.props.children)||Array.isArray(this.props.children))r=Array.prototype.some.call(this.props.children,function(t){return Array.isArray(t)?Array.prototype.some.call(t,function(t){return e.isAnchor(t.props)}):e.isAnchor(t.props)});else{var n=this.props.children;r=this.isAnchor(n.props)}return r?this.renderDiv(t):this.renderUL(t)}},{key:"isAnchor",value:function(e){return e.href||e.onClick}},{key:"renderUL",value:function(e){var t=c["default"].map(e,function(e,t){return l.cloneElement(e,{listItem:!0})});return p["default"].createElement("ul",a({},this.props,{className:d["default"](this.props.className,"list-group")}),t)}},{key:"renderDiv",value:function(e){return p["default"].createElement("div",a({},this.props,{className:d["default"](this.props.className,"list-group")}),e)}}]),t}(p["default"].Component);h.propTypes={className:p["default"].PropTypes.string,id:p["default"].PropTypes.string},t["default"]=h,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(3),l=n(i),p=r(2),u=n(p),d=a["default"].createClass({displayName:"ListGroupItem",mixins:[l["default"]],propTypes:{bsStyle:a["default"].PropTypes.oneOf(["danger","info","success","warning"]),className:a["default"].PropTypes.string,active:a["default"].PropTypes.any,disabled:a["default"].PropTypes.any,header:a["default"].PropTypes.node,listItem:a["default"].PropTypes.bool,onClick:a["default"].PropTypes.func,eventKey:a["default"].PropTypes.any,href:a["default"].PropTypes.string,target:a["default"].PropTypes.string},getDefaultProps:function(){return{bsClass:"list-group-item"}},render:function(){var e=this.getBsClassSet();return e.active=this.props.active,e.disabled=this.props.disabled,this.props.href||this.props.onClick?this.renderAnchor(e):this.props.listItem?this.renderLi(e):this.renderSpan(e)},renderLi:function(e){return a["default"].createElement("li",o({},this.props,{className:u["default"](this.props.className,e)}),this.props.header?this.renderStructuredContent():this.props.children)},renderAnchor:function(e){return a["default"].createElement("a",o({},this.props,{className:u["default"](this.props.className,e)}),this.props.header?this.renderStructuredContent():this.props.children)},renderSpan:function(e){return a["default"].createElement("span",o({},this.props,{className:u["default"](this.props.className,e)}),this.props.header?this.renderStructuredContent():this.props.children)},renderStructuredContent:function(){var e=void 0;e=a["default"].isValidElement(this.props.header)?s.cloneElement(this.props.header,{key:"header",className:u["default"](this.props.header.props.className,"list-group-item-heading")}):a["default"].createElement("h4",{key:"header",className:"list-group-item-heading"},this.props.header);var t=a["default"].createElement("p",{key:"content",className:"list-group-item-text"},this.props.children);return[e,t]}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=a["default"].createClass({displayName:"MenuItem",propTypes:{header:a["default"].PropTypes.bool,divider:a["default"].PropTypes.bool,href:a["default"].PropTypes.string,title:a["default"].PropTypes.string,target:a["default"].PropTypes.string,onSelect:a["default"].PropTypes.func,eventKey:a["default"].PropTypes.any,active:a["default"].PropTypes.bool},getDefaultProps:function(){return{href:"#",active:!1}},handleClick:function(e){this.props.onSelect&&(e.preventDefault(),this.props.onSelect(this.props.eventKey,this.props.href,this.props.target))},renderAnchor:function(){return a["default"].createElement("a",{onClick:this.handleClick,href:this.props.href,target:this.props.target,title:this.props.title,tabIndex:"-1"},this.props.children)},render:function(){var e={"dropdown-header":this.props.header,divider:this.props.divider,active:this.props.active},t=null;return this.props.header?t=this.props.children:this.props.divider||(t=this.renderAnchor()),a["default"].createElement("li",o({},this.props,{role:"presentation",title:null,href:null,className:l["default"](this.props.className,e)}),t)}});t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=r(10),f=n(d),c=r(5),h=n(c),m=r(12),v=n(m),y=a["default"].createClass({displayName:"Modal",mixins:[u["default"],f["default"]],propTypes:{title:a["default"].PropTypes.node,backdrop:a["default"].PropTypes.oneOf(["static",!0,!1]),keyboard:a["default"].PropTypes.bool,closeButton:a["default"].PropTypes.bool,animation:a["default"].PropTypes.bool,onRequestHide:a["default"].PropTypes.func.isRequired,dialogClassName:a["default"].PropTypes.string},getDefaultProps:function(){return{bsClass:"modal",backdrop:!0,keyboard:!0,animation:!0,closeButton:!0}},render:function(){var e={display:"block"},t=this.getBsClassSet();delete t.modal,t["modal-dialog"]=!0;var r={modal:!0,fade:this.props.animation,"in":!this.props.animation||!document.querySelectorAll},n=a["default"].createElement("div",o({},this.props,{title:null,tabIndex:"-1",role:"dialog",style:e,className:l["default"](this.props.className,r),onClick:this.props.backdrop===!0?this.handleBackdropClick:null,ref:"modal"}),a["default"].createElement("div",{className:l["default"](this.props.dialogClassName,t)},a["default"].createElement("div",{className:"modal-content"},this.props.title?this.renderHeader():null,this.props.children)));return this.props.backdrop?this.renderBackdrop(n):n},renderBackdrop:function(e){var t={"modal-backdrop":!0,fade:this.props.animation};t["in"]=!this.props.animation||!document.querySelectorAll;var r=this.props.backdrop===!0?this.handleBackdropClick:null;return a["default"].createElement("div",null,a["default"].createElement("div",{className:l["default"](t),ref:"backdrop",onClick:r}),e)},renderHeader:function(){var e=void 0;return this.props.closeButton&&(e=a["default"].createElement("button",{type:"button",className:"close","aria-hidden":"true",onClick:this.props.onRequestHide},"×")),a["default"].createElement("div",{className:"modal-header"},e,this.renderTitle())},renderTitle:function(){return a["default"].isValidElement(this.props.title)?this.props.title:a["default"].createElement("h4",{className:"modal-title"},this.props.title)},iosClickHack:function(){a["default"].findDOMNode(this.refs.modal).onclick=function(){},a["default"].findDOMNode(this.refs.backdrop).onclick=function(){}},componentDidMount:function(){this._onDocumentKeyupListener=v["default"].listen(h["default"].ownerDocument(this),"keyup",this.handleDocumentKeyUp);var e=this.props.container&&a["default"].findDOMNode(this.props.container)||h["default"].ownerDocument(this).body;e.className+=e.className.length?" modal-open":"modal-open",this.props.backdrop&&this.iosClickHack()},componentDidUpdate:function(e){this.props.backdrop&&this.props.backdrop!==e.backdrop&&this.iosClickHack()},componentWillUnmount:function(){this._onDocumentKeyupListener.remove();var e=this.props.container&&a["default"].findDOMNode(this.props.container)||h["default"].ownerDocument(this).body;e.className=e.className.replace(/ ?modal-open/,"")},handleBackdropClick:function(e){e.target===e.currentTarget&&this.props.onRequestHide()},handleDocumentKeyUp:function(e){this.props.keyboard&&27===e.keyCode&&this.props.onRequestHide()}});t["default"]=y,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(17),i=n(a),l=r(6),p=n(l),u=r(30),d=n(u),f=s["default"].createClass({displayName:"ModalTrigger",mixins:[i["default"]],propTypes:{modal:s["default"].PropTypes.node.isRequired},getInitialState:function(){return{isOverlayShown:!1}},show:function(){this.setState({isOverlayShown:!0})},hide:function(){this.setState({isOverlayShown:!1})},toggle:function(){this.setState({isOverlayShown:!this.state.isOverlayShown})},renderOverlay:function(){return this.state.isOverlayShown?o.cloneElement(this.props.modal,{onRequestHide:this.hide}):s["default"].createElement("span",null)},render:function(){var e=s["default"].Children.only(this.props.children),t={};return t.onClick=p["default"](e.props.onClick,this.toggle),t.onMouseOver=p["default"](e.props.onMouseOver,this.props.onMouseOver),t.onMouseOut=p["default"](e.props.onMouseOut,this.props.onMouseOut),t.onFocus=p["default"](e.props.onFocus,this.props.onFocus),t.onBlur=p["default"](e.props.onBlur,this.props.onBlur),o.cloneElement(e,t)}});f.withContext=d["default"](f,"modal"),t["default"]=f,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(3),l=n(i),p=r(2),u=n(p),d=r(4),f=n(d),c=r(6),h=n(c),m=a["default"].createClass({displayName:"Navbar",mixins:[l["default"]],propTypes:{fixedTop:a["default"].PropTypes.bool,fixedBottom:a["default"].PropTypes.bool,staticTop:a["default"].PropTypes.bool,inverse:a["default"].PropTypes.bool,fluid:a["default"].PropTypes.bool,role:a["default"].PropTypes.string,componentClass:a["default"].PropTypes.node.isRequired,brand:a["default"].PropTypes.node,toggleButton:a["default"].PropTypes.node,toggleNavKey:a["default"].PropTypes.oneOfType([a["default"].PropTypes.string,a["default"].PropTypes.number]),onToggle:a["default"].PropTypes.func,navExpanded:a["default"].PropTypes.bool,defaultNavExpanded:a["default"].PropTypes.bool},getDefaultProps:function(){return{bsClass:"navbar",bsStyle:"default",role:"navigation",componentClass:"nav"}},getInitialState:function(){return{navExpanded:this.props.defaultNavExpanded}},shouldComponentUpdate:function(){return!this._isChanging},handleToggle:function(){this.props.onToggle&&(this._isChanging=!0,this.props.onToggle(),this._isChanging=!1),this.setState({navExpanded:!this.state.navExpanded})},isNavExpanded:function(){return null!=this.props.navExpanded?this.props.navExpanded:this.state.navExpanded},render:function(){var e=this.getBsClassSet(),t=this.props.componentClass;return e["navbar-fixed-top"]=this.props.fixedTop,e["navbar-fixed-bottom"]=this.props.fixedBottom,e["navbar-static-top"]=this.props.staticTop,e["navbar-inverse"]=this.props.inverse,a["default"].createElement(t,o({},this.props,{className:u["default"](this.props.className,e)}),a["default"].createElement("div",{className:this.props.fluid?"container-fluid":"container"},this.props.brand||this.props.toggleButton||null!=this.props.toggleNavKey?this.renderHeader():null,f["default"].map(this.props.children,this.renderChild)))},renderChild:function(e,t){return s.cloneElement(e,{navbar:!0,collapsible:null!=this.props.toggleNavKey&&this.props.toggleNavKey===e.props.eventKey,expanded:null!=this.props.toggleNavKey&&this.props.toggleNavKey===e.props.eventKey&&this.isNavExpanded(),key:e.key?e.key:t})},renderHeader:function(){var e=void 0;return this.props.brand&&(e=a["default"].isValidElement(this.props.brand)?s.cloneElement(this.props.brand,{className:u["default"](this.props.brand.props.className,"navbar-brand")}):a["default"].createElement("span",{className:"navbar-brand"},this.props.brand)),a["default"].createElement("div",{className:"navbar-header"},e,this.props.toggleButton||null!=this.props.toggleNavKey?this.renderToggleButton():null)},renderToggleButton:function(){var e=void 0;return a["default"].isValidElement(this.props.toggleButton)?s.cloneElement(this.props.toggleButton,{className:u["default"](this.props.toggleButton.props.className,"navbar-toggle"),onClick:h["default"](this.handleToggle,this.props.toggleButton.props.onClick)}):(e=null!=this.props.toggleButton?this.props.toggleButton:[a["default"].createElement("span",{className:"sr-only",key:0},"Toggle navigation"),a["default"].createElement("span",{className:"icon-bar",key:1}),a["default"].createElement("span",{className:"icon-bar",key:2}),a["default"].createElement("span",{className:"icon-bar",key:3})],a["default"].createElement("button",{className:"navbar-toggle",type:"button",onClick:this.handleToggle},e))}});t["default"]=m,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return Array.isArray(t)?t.indexOf(e)>=0:e===t}Object.defineProperty(t,"__esModule",{value:!0});var s=r(1),a=n(s),i=r(17),l=n(i),p=r(60),u=n(p),d=r(6),f=n(d),c=r(30),h=n(c),m=r(5),v=n(m),y=r(13),b=n(y),g=a["default"].createClass({displayName:"OverlayTrigger",mixins:[l["default"]],propTypes:{trigger:a["default"].PropTypes.oneOfType([a["default"].PropTypes.oneOf(["manual","click","hover","focus"]),a["default"].PropTypes.arrayOf(a["default"].PropTypes.oneOf(["click","hover","focus"]))]),placement:a["default"].PropTypes.oneOf(["top","right","bottom","left"]),delay:a["default"].PropTypes.number,delayShow:a["default"].PropTypes.number,delayHide:a["default"].PropTypes.number,defaultOverlayShown:a["default"].PropTypes.bool,overlay:a["default"].PropTypes.node.isRequired,containerPadding:a["default"].PropTypes.number,rootClose:a["default"].PropTypes.bool},getDefaultProps:function(){return{placement:"right",trigger:["hover","focus"],containerPadding:0}},getInitialState:function(){return{isOverlayShown:null==this.props.defaultOverlayShown?!1:this.props.defaultOverlayShown,overlayLeft:null,overlayTop:null,arrowOffsetLeft:null,arrowOffsetTop:null}},show:function(){this.setState({isOverlayShown:!0},function(){this.updateOverlayPosition()})},hide:function(){this.setState({isOverlayShown:!1})},toggle:function(){this.state.isOverlayShown?this.hide():this.show()},renderOverlay:function(){if(!this.state.isOverlayShown)return a["default"].createElement("span",null);var e=s.cloneElement(this.props.overlay,{onRequestHide:this.hide,placement:this.props.placement,positionLeft:this.state.overlayLeft,positionTop:this.state.overlayTop,arrowOffsetLeft:this.state.arrowOffsetLeft,arrowOffsetTop:this.state.arrowOffsetTop});return this.props.rootClose?a["default"].createElement(u["default"],{onRootClose:this.hide},e):e},render:function(){var e=a["default"].Children.only(this.props.children);if("manual"===this.props.trigger)return e;var t={};return t.onClick=f["default"](e.props.onClick,this.props.onClick),o("click",this.props.trigger)&&(t.onClick=f["default"](this.toggle,t.onClick)),o("hover",this.props.trigger)&&(t.onMouseOver=f["default"](this.handleDelayedShow,this.props.onMouseOver),t.onMouseOut=f["default"](this.handleDelayedHide,this.props.onMouseOut)),o("focus",this.props.trigger)&&(t.onFocus=f["default"](this.handleDelayedShow,this.props.onFocus),t.onBlur=f["default"](this.handleDelayedHide,this.props.onBlur)),s.cloneElement(e,t)},componentWillUnmount:function(){clearTimeout(this._hoverDelay)},componentDidMount:function(){this.props.defaultOverlayShown&&this.updateOverlayPosition()},handleDelayedShow:function(){if(null!=this._hoverDelay)return clearTimeout(this._hoverDelay),void(this._hoverDelay=null);var e=null!=this.props.delayShow?this.props.delayShow:this.props.delay;return e?void(this._hoverDelay=setTimeout(function(){this._hoverDelay=null,this.show()}.bind(this),e)):void this.show()},handleDelayedHide:function(){if(null!=this._hoverDelay)return clearTimeout(this._hoverDelay),void(this._hoverDelay=null);var e=null!=this.props.delayHide?this.props.delayHide:this.props.delay;return e?void(this._hoverDelay=setTimeout(function(){this._hoverDelay=null,this.hide()}.bind(this),e)):void this.hide()},updateOverlayPosition:function(){this.isMounted()&&this.setState(this.calcOverlayPosition())},calcOverlayPosition:function(){var e=this.getPosition(),t=this.getOverlayDOMNode(),r=t.offsetHeight,n=t.offsetWidth,o=this.props.placement,s=void 0,a=void 0,i=void 0,l=void 0;if("left"===o||"right"===o){a=e.top+(e.height-r)/2,s="left"===o?e.left-n:e.left+e.width;var p=this._getTopDelta(a,r);a+=p,l=50*(1-2*p/r)+"%",i=null}else{if("top"!==o&&"bottom"!==o)throw new Error('calcOverlayPosition(): No such placement of "'+this.props.placement+'" found.');s=e.left+(e.width-n)/2,a="top"===o?e.top-r:e.top+e.height;var u=this._getLeftDelta(s,n);s+=u,i=50*(1-2*u/n)+"%",l=null}return{overlayLeft:s,overlayTop:a,arrowOffsetLeft:i,arrowOffsetTop:l}},_getTopDelta:function(e,t){var r=this._getContainerDimensions(),n=r.scroll,o=r.height,s=this.props.containerPadding,a=e-s-n,i=e+s-n+t;return 0>a?-a:i>o?o-i:0},_getLeftDelta:function(e,t){var r=this._getContainerDimensions(),n=r.width,o=this.props.containerPadding,s=e-o,a=e+o+t;return 0>s?-s:a>n?n-a:0},_getContainerDimensions:function(){var e=this.getContainerDOMNode(),t=void 0,r=void 0;return"BODY"===e.tagName?(t=window.innerWidth,r=window.innerHeight):(t=e.offsetWidth,r=e.offsetHeight),{width:t,height:r,scroll:e.scrollTop}},getPosition:function(){var e=a["default"].findDOMNode(this),t=this.getContainerDOMNode(),r="BODY"===t.tagName?v["default"].getOffset(e):v["default"].getPosition(e,t);return b["default"]({},r,{height:e.offsetHeight,width:e.offsetWidth})}});g.withContext=h["default"](g,"overlay"),t["default"]=g,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=a["default"].createClass({displayName:"PageHeader",render:function(){return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,"page-header")}),a["default"].createElement("h1",null,this.props.children))}});t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=a["default"].createClass({displayName:"PageItem",propTypes:{href:a["default"].PropTypes.string,target:a["default"].PropTypes.string,title:a["default"].PropTypes.string,disabled:a["default"].PropTypes.bool,previous:a["default"].PropTypes.bool,next:a["default"].PropTypes.bool,onSelect:a["default"].PropTypes.func,eventKey:a["default"].PropTypes.any},getDefaultProps:function(){return{href:"#"}},render:function(){var e={disabled:this.props.disabled,previous:this.props.previous,next:this.props.next};return a["default"].createElement("li",o({},this.props,{className:l["default"](this.props.className,e)}),a["default"].createElement("a",{href:this.props.href,title:this.props.title,target:this.props.target,onClick:this.handleSelect,ref:"anchor"},this.props.children))},handleSelect:function(e){this.props.onSelect&&(e.preventDefault(),this.props.disabled||this.props.onSelect(this.props.eventKey,this.props.href,this.props.target))}});t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(4),u=n(p),d=r(6),f=n(d),c=a["default"].createClass({displayName:"Pager",propTypes:{onSelect:a["default"].PropTypes.func},render:function(){return a["default"].createElement("ul",o({},this.props,{className:l["default"](this.props.className,"pager")}),u["default"].map(this.props.children,this.renderPageItem))},renderPageItem:function(e,t){return s.cloneElement(e,{onSelect:f["default"](e.props.onSelect,this.props.onSelect),key:e.key?e.key:t})}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=r(7),f=n(d),c=r(19),h=n(c),m=a["default"].createClass({displayName:"Panel",mixins:[u["default"],f["default"]],propTypes:{collapsable:h["default"],collapsible:a["default"].PropTypes.bool,onSelect:a["default"].PropTypes.func,header:a["default"].PropTypes.node,id:a["default"].PropTypes.string,footer:a["default"].PropTypes.node,eventKey:a["default"].PropTypes.any},getDefaultProps:function(){return{bsClass:"panel",bsStyle:"default"}},handleSelect:function(e){e.selected=!0,this.props.onSelect?this.props.onSelect(e,this.props.eventKey):e.preventDefault(),e.selected&&this.handleToggle()},handleToggle:function(){this.setState({expanded:!this.state.expanded})},getCollapsibleDimensionValue:function(){return a["default"].findDOMNode(this.refs.panel).scrollHeight},getCollapsibleDOMNode:function(){return this.isMounted()&&this.refs&&this.refs.panel?a["default"].findDOMNode(this.refs.panel):null},render:function(){var e=this.getBsClassSet(),t=this.props.collapsible||this.props.collapsable;return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e),id:t?null:this.props.id,onSelect:null}),this.renderHeading(),t?this.renderCollapsableBody():this.renderBody(),this.renderFooter())},renderCollapsableBody:function(){var e=this.prefixClass("collapse");return a["default"].createElement("div",{className:l["default"](this.getCollapsibleClassSet(e)),id:this.props.id,ref:"panel","aria-expanded":this.isExpanded()?"true":"false"},this.renderBody())},renderBody:function(){function e(){return{key:l.length}}function t(t){l.push(s.cloneElement(t,e()))}function r(t){l.push(a["default"].createElement("div",o({className:u},e()),t))}function n(){0!==p.length&&(r(p),p=[])}var i=this.props.children,l=[],p=[],u=this.prefixClass("body");return Array.isArray(i)&&0!==i.length?(i.forEach(function(e){this.shouldRenderFill(e)?(n(),t(e)):p.push(e)}.bind(this)),n()):this.shouldRenderFill(i)?t(i):r(i),l},shouldRenderFill:function(e){return a["default"].isValidElement(e)&&null!=e.props.fill},renderHeading:function(){var e=this.props.header,t=this.props.collapsible||this.props.collapsable;if(!e)return null;if(!a["default"].isValidElement(e)||Array.isArray(e))e=t?this.renderCollapsableTitle(e):e;else{var r=l["default"](this.prefixClass("title"),e.props.className);e=t?s.cloneElement(e,{className:r,children:this.renderAnchor(e.props.children)}):s.cloneElement(e,{className:r})}return a["default"].createElement("div",{className:this.prefixClass("heading")},e)},renderAnchor:function(e){return a["default"].createElement("a",{href:"#"+(this.props.id||""),className:this.isExpanded()?null:"collapsed","aria-expanded":this.isExpanded()?"true":"false",onClick:this.handleSelect},e)},renderCollapsableTitle:function(e){return a["default"].createElement("h4",{className:this.prefixClass("title")},this.renderAnchor(e))},renderFooter:function(){return this.props.footer?a["default"].createElement("div",{className:this.prefixClass("footer")},this.props.footer):null}});t["default"]=m,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0})}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(1),i=n(a),l=r(2),p=n(l),u=r(3),d=n(u),f=r(10),c=n(f),h=i["default"].createClass({displayName:"Popover",mixins:[d["default"],c["default"]],propTypes:{placement:i["default"].PropTypes.oneOf(["top","right","bottom","left"]),positionLeft:i["default"].PropTypes.number,positionTop:i["default"].PropTypes.number,arrowOffsetLeft:i["default"].PropTypes.oneOfType([i["default"].PropTypes.number,i["default"].PropTypes.string]),arrowOffsetTop:i["default"].PropTypes.oneOfType([i["default"].PropTypes.number,i["default"].PropTypes.string]),title:i["default"].PropTypes.node,animation:i["default"].PropTypes.bool},getDefaultProps:function(){return{placement:"right",animation:!0}},render:function(){var e,t=(e={popover:!0},o(e,this.props.placement,!0),o(e,"in",!this.props.animation&&(null!=this.props.positionLeft||null!=this.props.positionTop)),o(e,"fade",this.props.animation),e),r={left:this.props.positionLeft,top:this.props.positionTop,display:"block"},n={left:this.props.arrowOffsetLeft,top:this.props.arrowOffsetTop};return i["default"].createElement("div",s({},this.props,{className:p["default"](this.props.className,t),style:r,title:null}),i["default"].createElement("div",{className:"arrow",style:n}),this.props.title?this.renderTitle():null,i["default"].createElement("div",{className:"popover-content"},this.props.children))},renderTitle:function(){return i["default"].createElement("h3",{className:"popover-title"},this.props.title)}});t["default"]=h,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(25),l=n(i),p=r(3),u=n(p),d=r(2),f=n(d),c=r(4),h=n(c),m=a["default"].createClass({displayName:"ProgressBar",propTypes:{min:a["default"].PropTypes.number,now:a["default"].PropTypes.number,max:a["default"].PropTypes.number,label:a["default"].PropTypes.node,srOnly:a["default"].PropTypes.bool,striped:a["default"].PropTypes.bool,active:a["default"].PropTypes.bool},mixins:[u["default"]],getDefaultProps:function(){return{bsClass:"progress-bar",min:0,max:100}},getPercentage:function(e,t,r){var n=1e3;return Math.round((e-t)/(r-t)*100*n)/n},render:function(){var e={progress:!0};return this.props.active?(e["progress-striped"]=!0,e.active=!0):this.props.striped&&(e["progress-striped"]=!0),h["default"].hasValidComponent(this.props.children)?a["default"].createElement("div",o({},this.props,{className:f["default"](this.props.className,e)}),h["default"].map(this.props.children,this.renderChildBar)):this.props.isChild?this.renderProgressBar():a["default"].createElement("div",o({},this.props,{className:f["default"](this.props.className,e)}),this.renderProgressBar())},renderChildBar:function(e,t){return s.cloneElement(e,{isChild:!0,key:e.key?e.key:t})},renderProgressBar:function(){var e=this.getPercentage(this.props.now,this.props.min,this.props.max),t=void 0;"string"==typeof this.props.label?t=this.renderLabel(e):this.props.label&&(t=this.props.label),this.props.srOnly&&(t=this.renderScreenReaderOnlyLabel(t));var r=this.getBsClassSet();return a["default"].createElement("div",o({},this.props,{className:f["default"](this.props.className,r),role:"progressbar",style:{width:e+"%"},"aria-valuenow":this.props.now,"aria-valuemin":this.props.min,"aria-valuemax":this.props.max}),t)},renderLabel:function(e){var t=this.props.interpolateClass||l["default"];return a["default"].createElement(t,{now:this.props.now,min:this.props.min,max:this.props.max,percent:e,bsStyle:this.props.bsStyle},this.props.label)},renderScreenReaderOnlyLabel:function(e){return a["default"].createElement("span",{className:"sr-only"},e)}});t["default"]=m,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}function a(e,t){for(;e;){if(e===t)return!0;e=e.parentNode}return!1}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=function(e,t,r){for(var n=!0;n;){var o=e,s=t,a=r;i=p=l=void 0,n=!1;var i=Object.getOwnPropertyDescriptor(o,s);if(void 0!==i){if("value"in i)return i.value;var l=i.get;return void 0===l?void 0:l.call(a)}var p=Object.getPrototypeOf(o);if(null===p)return void 0;e=p,t=s,r=a,n=!0}},p=r(1),u=n(p),d=r(5),f=n(d),c=r(12),h=n(c),m=function(e){function t(e){o(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.handleDocumentClick=this.handleDocumentClick.bind(this),this.handleDocumentKeyUp=this.handleDocumentKeyUp.bind(this)}return s(t,e),i(t,[{key:"bindRootCloseHandlers",value:function(){var e=f["default"].ownerDocument(this);this._onDocumentClickListener=h["default"].listen(e,"click",this.handleDocumentClick),this._onDocumentKeyupListener=h["default"].listen(e,"keyup",this.handleDocumentKeyUp)}},{key:"handleDocumentClick",value:function(e){a(e.target,u["default"].findDOMNode(this))||this.props.onRootClose()}},{key:"handleDocumentKeyUp",value:function(e){27===e.keyCode&&this.props.onRootClose()}},{key:"unbindRootCloseHandlers",value:function(){this._onDocumentClickListener&&this._onDocumentClickListener.remove(),this._onDocumentKeyupListener&&this._onDocumentKeyupListener.remove()}},{key:"componentDidMount",value:function(){this.bindRootCloseHandlers()}},{key:"render",value:function(){return u["default"].Children.only(this.props.children)}},{key:"componentWillUnmount",value:function(){this.unbindRootCloseHandlers()}}]),t}(u["default"].Component);t["default"]=m,m.propTypes={onRootClose:u["default"].PropTypes.func.isRequired},e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e; },s=r(1),a=n(s),i=r(2),l=n(i),p=a["default"].createClass({displayName:"Row",propTypes:{componentClass:a["default"].PropTypes.node.isRequired},getDefaultProps:function(){return{componentClass:"div"}},render:function(){var e=this.props.componentClass;return a["default"].createElement(e,o({},this.props,{className:l["default"](this.props.className,"row")}),this.props.children)}});t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=r(16),f=n(d),c=r(9),h=n(c),m=r(14),v=n(m),y=r(15),b=n(y),g=a["default"].createClass({displayName:"SplitButton",mixins:[u["default"],f["default"]],propTypes:{pullRight:a["default"].PropTypes.bool,title:a["default"].PropTypes.node,href:a["default"].PropTypes.string,id:a["default"].PropTypes.string,target:a["default"].PropTypes.string,dropdownTitle:a["default"].PropTypes.node,dropup:a["default"].PropTypes.bool,onClick:a["default"].PropTypes.func,onSelect:a["default"].PropTypes.func,disabled:a["default"].PropTypes.bool},getDefaultProps:function(){return{dropdownTitle:"Toggle dropdown"}},render:function(){var e={open:this.state.open,dropup:this.props.dropup},t=a["default"].createElement(h["default"],o({},this.props,{ref:"button",onClick:this.handleButtonClick,title:null,id:null}),this.props.title),r=a["default"].createElement(h["default"],o({},this.props,{ref:"dropdownButton",className:l["default"](this.props.className,"dropdown-toggle"),onClick:this.handleDropdownClick,title:null,href:null,target:null,id:null}),a["default"].createElement("span",{className:"sr-only"},this.props.dropdownTitle),a["default"].createElement("span",{className:"caret"}),a["default"].createElement("span",{style:{letterSpacing:"-.3em"}}," "));return a["default"].createElement(v["default"],{bsSize:this.props.bsSize,className:l["default"](e),id:this.props.id},t,r,a["default"].createElement(b["default"],{ref:"menu",onSelect:this.handleOptionSelect,"aria-labelledby":this.props.id,pullRight:this.props.pullRight},this.props.children))},handleButtonClick:function(e){this.state.open&&this.setDropdownState(!1),this.props.onClick&&this.props.onClick(e,this.props.href,this.props.target)},handleDropdownClick:function(e){e.preventDefault(),this.setDropdownState(!this.state.open)},handleOptionSelect:function(e){this.props.onSelect&&this.props.onSelect(e),this.setDropdownState(!1)}});t["default"]=g,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(4),u=n(p),d=r(6),f=n(d),c=r(3),h=n(c),m=a["default"].createClass({displayName:"SubNav",mixins:[h["default"]],propTypes:{onSelect:a["default"].PropTypes.func,active:a["default"].PropTypes.bool,activeHref:a["default"].PropTypes.string,activeKey:a["default"].PropTypes.any,disabled:a["default"].PropTypes.bool,eventKey:a["default"].PropTypes.any,href:a["default"].PropTypes.string,title:a["default"].PropTypes.string,text:a["default"].PropTypes.node,target:a["default"].PropTypes.string},getDefaultProps:function(){return{bsClass:"nav"}},handleClick:function(e){this.props.onSelect&&(e.preventDefault(),this.props.disabled||this.props.onSelect(this.props.eventKey,this.props.href,this.props.target))},isActive:function(){return this.isChildActive(this)},isChildActive:function(e){var t=this;if(e.props.active)return!0;if(null!=this.props.activeKey&&this.props.activeKey===e.props.eventKey)return!0;if(null!=this.props.activeHref&&this.props.activeHref===e.props.href)return!0;if(e.props.children){var r=function(){var r=!1;return u["default"].forEach(e.props.children,function(e){this.isChildActive(e)&&(r=!0)},t),{v:r}}();if("object"==typeof r)return r.v}return!1},getChildActiveProp:function(e){return e.props.active?!0:null!=this.props.activeKey&&e.props.eventKey===this.props.activeKey?!0:null!=this.props.activeHref&&e.props.href===this.props.activeHref?!0:e.props.active},render:function(){var e={active:this.isActive(),disabled:this.props.disabled};return a["default"].createElement("li",o({},this.props,{className:l["default"](this.props.className,e)}),a["default"].createElement("a",{href:this.props.href,title:this.props.title,target:this.props.target,onClick:this.handleClick,ref:"anchor"},this.props.text),a["default"].createElement("ul",{className:"nav"},u["default"].map(this.props.children,this.renderNavItem)))},renderNavItem:function(e,t){return s.cloneElement(e,{active:this.getChildActiveProp(e),onSelect:f["default"](e.props.onSelect,this.props.onSelect),key:e.key?e.key:t})}});t["default"]=m,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(18),u=n(p),d=a["default"].createClass({displayName:"TabPane",propTypes:{active:a["default"].PropTypes.bool,animation:a["default"].PropTypes.bool,onAnimateOutEnd:a["default"].PropTypes.func,disabled:a["default"].PropTypes.bool},getDefaultProps:function(){return{animation:!0}},getInitialState:function(){return{animateIn:!1,animateOut:!1}},componentWillReceiveProps:function(e){this.props.animation&&(this.state.animateIn||!e.active||this.props.active?this.state.animateOut||e.active||!this.props.active||this.setState({animateOut:!0}):this.setState({animateIn:!0}))},componentDidUpdate:function(){this.state.animateIn&&setTimeout(this.startAnimateIn,0),this.state.animateOut&&u["default"].addEndEventListener(a["default"].findDOMNode(this),this.stopAnimateOut)},startAnimateIn:function(){this.isMounted()&&this.setState({animateIn:!1})},stopAnimateOut:function(){this.isMounted()&&(this.setState({animateOut:!1}),this.props.onAnimateOutEnd&&this.props.onAnimateOutEnd())},render:function(){var e={"tab-pane":!0,fade:!0,active:this.props.active||this.state.animateOut,"in":this.props.active&&!this.state.animateIn};return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=void 0;return d["default"].forEach(e,function(e){null==t&&(t=e.props.eventKey)}),t}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(1),i=n(a),l=r(3),p=n(l),u=r(4),d=n(u),f=r(26),c=n(f),h=r(27),m=n(h),v=i["default"].createClass({displayName:"TabbedArea",mixins:[p["default"]],propTypes:{activeKey:i["default"].PropTypes.any,defaultActiveKey:i["default"].PropTypes.any,bsStyle:i["default"].PropTypes.oneOf(["tabs","pills"]),animation:i["default"].PropTypes.bool,id:i["default"].PropTypes.string,onSelect:i["default"].PropTypes.func},getDefaultProps:function(){return{bsStyle:"tabs",animation:!0}},getInitialState:function(){var e=null!=this.props.defaultActiveKey?this.props.defaultActiveKey:o(this.props.children);return{activeKey:e,previousActiveKey:null}},componentWillReceiveProps:function(e){null!=e.activeKey&&e.activeKey!==this.props.activeKey&&this.setState({previousActiveKey:this.props.activeKey})},handlePaneAnimateOutEnd:function(){this.setState({previousActiveKey:null})},render:function(){function e(e){return null!=e.props.tab?this.renderTab(e):null}var t=null!=this.props.activeKey?this.props.activeKey:this.state.activeKey,r=i["default"].createElement(c["default"],s({},this.props,{activeKey:t,onSelect:this.handleSelect,ref:"tabs"}),d["default"].map(this.props.children,e,this));return i["default"].createElement("div",null,r,i["default"].createElement("div",{id:this.props.id,className:"tab-content",ref:"panes"},d["default"].map(this.props.children,this.renderPane)))},getActiveKey:function(){return null!=this.props.activeKey?this.props.activeKey:this.state.activeKey},renderPane:function(e,t){var r=this.getActiveKey();return a.cloneElement(e,{active:e.props.eventKey===r&&(null==this.state.previousActiveKey||!this.props.animation),key:e.key?e.key:t,animation:this.props.animation,onAnimateOutEnd:null!=this.state.previousActiveKey&&e.props.eventKey===this.state.previousActiveKey?this.handlePaneAnimateOutEnd:null})},renderTab:function(e){var t=e.props,r=t.eventKey,n=t.className,o=t.tab,s=t.disabled;return i["default"].createElement(m["default"],{ref:"tab"+r,eventKey:r,className:n,disabled:s},o)},shouldComponentUpdate:function(){return!this._isChanging},handleSelect:function(e){this.props.onSelect?(this._isChanging=!0,this.props.onSelect(e),this._isChanging=!1):e!==this.getActiveKey()&&this.setState({activeKey:e,previousActiveKey:this.getActiveKey()})}});t["default"]=v,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=a["default"].createClass({displayName:"Table",propTypes:{striped:a["default"].PropTypes.bool,bordered:a["default"].PropTypes.bool,condensed:a["default"].PropTypes.bool,hover:a["default"].PropTypes.bool,responsive:a["default"].PropTypes.bool},render:function(){var e={table:!0,"table-striped":this.props.striped,"table-bordered":this.props.bordered,"table-condensed":this.props.condensed,"table-hover":this.props.hover},t=a["default"].createElement("table",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children);return this.props.responsive?a["default"].createElement("div",{className:"table-responsive"},t):t}});t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=a["default"].createClass({displayName:"Thumbnail",mixins:[u["default"]],getDefaultProps:function(){return{bsClass:"thumbnail"}},render:function(){var e=this.getBsClassSet();return this.props.href?a["default"].createElement("a",o({},this.props,{href:this.props.href,className:l["default"](this.props.className,e)}),a["default"].createElement("img",{src:this.props.src,alt:this.props.alt})):this.props.children?a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),a["default"].createElement("img",{src:this.props.src,alt:this.props.alt}),a["default"].createElement("div",{className:"caption"},this.props.children)):a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),a["default"].createElement("img",{src:this.props.src,alt:this.props.alt}))}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0})}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(1),i=n(a),l=r(2),p=n(l),u=r(3),d=n(u),f=r(10),c=n(f),h=i["default"].createClass({displayName:"Tooltip",mixins:[d["default"],c["default"]],propTypes:{placement:i["default"].PropTypes.oneOf(["top","right","bottom","left"]),positionLeft:i["default"].PropTypes.number,positionTop:i["default"].PropTypes.number,arrowOffsetLeft:i["default"].PropTypes.oneOfType([i["default"].PropTypes.number,i["default"].PropTypes.string]),arrowOffsetTop:i["default"].PropTypes.oneOfType([i["default"].PropTypes.number,i["default"].PropTypes.string]),animation:i["default"].PropTypes.bool},getDefaultProps:function(){return{placement:"right",animation:!0}},render:function(){var e,t=(e={tooltip:!0},o(e,this.props.placement,!0),o(e,"in",!this.props.animation&&(null!=this.props.positionLeft||null!=this.props.positionTop)),o(e,"fade",this.props.animation),e),r={left:this.props.positionLeft,top:this.props.positionTop},n={left:this.props.arrowOffsetLeft,top:this.props.arrowOffsetTop};return i["default"].createElement("div",s({},this.props,{className:p["default"](this.props.className,t),style:r}),i["default"].createElement("div",{className:"tooltip-arrow",style:n}),i["default"].createElement("div",{className:"tooltip-inner"},this.props.children))}});t["default"]=h,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),p=r(3),u=n(p),d=a["default"].createClass({displayName:"Well",mixins:[u["default"]],getDefaultProps:function(){return{bsClass:"well"}},render:function(){var e=this.getBsClassSet();return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]}])}); //# sourceMappingURL=react-bootstrap.min.js.map
examples/with-mux-video/pages/asset/[id].js
zeit/next.js
import { useEffect } from 'react' import Router, { useRouter } from 'next/router' import Link from 'next/link' import useSwr from 'swr' import Spinner from '../../components/spinner' import ErrorMessage from '../../components/error-message' import UploadPage from '../../components/upload-page' const fetcher = (url) => { return fetch(url).then((res) => res.json()) } export default function Asset() { const router = useRouter() const { data, error } = useSwr( () => (router.query.id ? `/api/asset/${router.query.id}` : null), fetcher, { refreshInterval: 5000 } ) const asset = data && data.asset useEffect(() => { if (asset && asset.playback_id && asset.status === 'ready') { Router.push(`/v/${asset.playback_id}`) } }, [asset]) let errorMessage if (error) { errorMessage = 'Error fetching api' } if (data && data.error) { errorMessage = data.error } if (asset && asset.status === 'errored') { const message = asset.errors && asset.errors.messages[0] errorMessage = `Error creating this asset: ${message}` } return ( <UploadPage> {errorMessage ? ( <> <ErrorMessage message={errorMessage} /> <p> Go{' '} <Link href="/"> <a>back home</a> </Link>{' '} to upload another video. </p> </> ) : ( <> <div>Preparing...</div> <Spinner /> </> )} </UploadPage> ) }
ajax/libs/choices.js/1.1.7/choices.js
extend1994/cdnjs
/*! choices.js v1.1.7 | (c) 2016 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/assets/scripts/dist/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _fuse = __webpack_require__(2); var _fuse2 = _interopRequireDefault(_fuse); var _index = __webpack_require__(3); var _index2 = _interopRequireDefault(_index); var _index3 = __webpack_require__(22); var _utils = __webpack_require__(23); __webpack_require__(24); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Choices */ var Choices = function () { function Choices() { var _this = this; var element = arguments.length <= 0 || arguments[0] === undefined ? '[data-choice]' : arguments[0]; var userConfig = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, Choices); // If there are multiple elements, create a new instance // for each element besides the first one (as that already has an instance) if ((0, _utils.isType)('String', element)) { var elements = document.querySelectorAll(element); if (elements.length > 1) { for (var i = 1; i < elements.length; i++) { var el = elements[i]; new Choices(el, userConfig); } } } var defaultConfig = { items: [], choices: [], maxItemCount: -1, addItems: true, removeItems: true, removeItemButton: false, editItems: false, duplicateItems: true, delimiter: ',', paste: true, search: true, flip: true, regexFilter: null, sortFilter: _utils.sortByAlpha, sortFields: ['label', 'value'], placeholder: true, placeholderValue: null, prependValue: null, appendValue: null, loadingText: 'Loading...', noResultsText: 'No results round', noChoicesText: 'No choices to choose from', classNames: { containerOuter: 'choices', containerInner: 'choices__inner', input: 'choices__input', inputCloned: 'choices__input--cloned', list: 'choices__list', listItems: 'choices__list--multiple', listSingle: 'choices__list--single', listDropdown: 'choices__list--dropdown', item: 'choices__item', itemSelectable: 'choices__item--selectable', itemDisabled: 'choices__item--disabled', itemChoice: 'choices__item--choice', placeholder: 'choices__placeholder', group: 'choices__group', groupHeading: 'choices__heading', button: 'choices__button', activeState: 'is-active', focusState: 'is-focused', openState: 'is-open', disabledState: 'is-disabled', highlightedState: 'is-highlighted', hiddenState: 'is-hidden', flippedState: 'is-flipped', loadingState: 'is-loading' }, callbackOnInit: function callbackOnInit() {}, callbackOnAddItem: function callbackOnAddItem(id, value, passedInput) {}, callbackOnRemoveItem: function callbackOnRemoveItem(id, value, passedInput) {}, callbackOnHighlightItem: function callbackOnHighlightItem(id, value, passedInput) {}, callbackOnUnhighlightItem: function callbackOnUnhighlightItem(id, value, passedInput) {}, callbackOnChange: function callbackOnChange(value, passedInput) {} }; // Merge options with user options this.config = (0, _utils.extend)(defaultConfig, userConfig); // Create data store this.store = new _index2.default(this.render); // State tracking this.initialised = false; this.currentState = {}; this.prevState = {}; this.currentValue = ''; // Retrieve triggering element (i.e. element with 'data-choice' trigger) this.passedElement = (0, _utils.isType)('String', element) ? document.querySelector(element) : element; this.highlightPosition = 0; this.canSearch = this.config.search; // Assing preset choices from passed object this.presetChoices = this.config.choices; // Assign preset items from passed object first this.presetItems = this.config.items; // Then add any values passed from attribute if (this.passedElement.value) { this.presetItems = this.presetItems.concat(this.passedElement.value.split(this.config.delimiter)); } // Bind methods this.init = this.init.bind(this); this.render = this.render.bind(this); this.destroy = this.destroy.bind(this); this.disable = this.disable.bind(this); // Bind event handlers this._onFocus = this._onFocus.bind(this); this._onBlur = this._onBlur.bind(this); this._onKeyUp = this._onKeyUp.bind(this); this._onKeyDown = this._onKeyDown.bind(this); this._onClick = this._onClick.bind(this); this._onTouchMove = this._onTouchMove.bind(this); this._onTouchEnd = this._onTouchEnd.bind(this); this._onMouseDown = this._onMouseDown.bind(this); this._onMouseOver = this._onMouseOver.bind(this); this._onPaste = this._onPaste.bind(this); this._onInput = this._onInput.bind(this); // Focus containerOuter but not show dropdown if true this.focusAndHideDropdown = false; // Monitor touch taps/scrolls this.wasTap = true; // Cutting the mustard var cuttingTheMustard = 'querySelector' in document && 'addEventListener' in document && 'classList' in document.createElement('div'); if (!cuttingTheMustard) console.error('Choices: Your browser doesn\'t support Choices'); // Input type check var canInit = this.passedElement && (0, _utils.isElement)(this.passedElement) && ['select-one', 'select-multiple', 'text'].some(function (type) { return type === _this.passedElement.type; }); if (canInit) { // If element has already been initalised with Choices if (this.passedElement.getAttribute('data-choice') === 'active') return; // Let's go this.init(); } else { console.error('Incompatible input passed'); } } /** * Initialise Choices * @return * @public */ _createClass(Choices, [{ key: 'init', value: function init() { var callback = arguments.length <= 0 || arguments[0] === undefined ? this.config.callbackOnInit : arguments[0]; if (this.initialised !== true) { // Set initialise flag this.initialised = true; // Create required elements this._createTemplates(); // Generate input markup this._createInput(); this.store.subscribe(this.render); // Render any items this.render(); // Trigger event listeners this._addEventListeners(); // Run callback if it is a function if (callback) { if ((0, _utils.isType)('Function', callback)) { callback(); } else { console.error('callbackOnInit: Callback is not a function'); } } } } /** * Destroy Choices and nullify values * @return * @public */ }, { key: 'destroy', value: function destroy() { this._removeEventListeners(); this.passedElement.classList.remove(this.config.classNames.input, this.config.classNames.hiddenState); this.passedElement.tabIndex = ''; this.passedElement.removeAttribute('style', 'display:none;'); this.passedElement.removeAttribute('aria-hidden'); this.containerOuter.outerHTML = this.passedElement.outerHTML; this.passedElement = null; this.userConfig = null; this.config = null; this.store = null; } /** * Select item (a selected item can be deleted) * @param {Element} item Element to select * @return {Object} Class instance * @public */ }, { key: 'highlightItem', value: function highlightItem(item) { if (!item) return; var id = item.id; this.store.dispatch((0, _index3.highlightItem)(id, true)); // Run callback if it is a function if (this.config.callbackOnHighlightItem) { var callback = this.config.callbackOnHighlightItem; if ((0, _utils.isType)('Function', callback)) { callback(id, item.value, this.passedElement); } else { console.error('callbackOnHighlightItem: Callback is not a function'); } } return this; } /** * Deselect item * @param {Element} item Element to de-select * @return {Object} Class instance * @public */ }, { key: 'unhighlightItem', value: function unhighlightItem(item) { if (!item) return; var id = item.id; this.store.dispatch((0, _index3.highlightItem)(id, false)); // Run callback if it is a function if (this.config.callbackOnUnhighlightItem) { var callback = this.config.callbackOnUnhighlightItem; if ((0, _utils.isType)('Function', callback)) { callback(id, item.value, this.passedElement); } else { console.error('callbackOnUnhighlightItem: Callback is not a function'); } } return this; } /** * Highlight items within store * @return {Object} Class instance * @public */ }, { key: 'highlightAll', value: function highlightAll() { var _this2 = this; var items = this.store.getItems(); items.forEach(function (item) { _this2.highlightItem(item); }); return this; } /** * Deselect items within store * @return {Object} Class instance * @public */ }, { key: 'unhighlightAll', value: function unhighlightAll() { var _this3 = this; var items = this.store.getItems(); items.forEach(function (item) { _this3.unhighlightItem(item); }); return this; } /** * Remove an item from the store by its value * @param {String} value Value to search for * @return {Object} Class instance * @public */ }, { key: 'removeItemsByValue', value: function removeItemsByValue(value) { var _this4 = this; if (!value || !(0, _utils.isType)('String', value)) { console.error('removeItemsByValue: No value was passed to be removed'); return; } var items = this.store.getItemsFilteredByActive(); items.forEach(function (item) { if (item.value === value) { _this4._removeItem(item); } }); return this; } /** * Remove all items from store array * @note Removed items are soft deleted * @param {Number} excludedId Optionally exclude item by ID * @return {Object} Class instance * @public */ }, { key: 'removeActiveItems', value: function removeActiveItems(excludedId) { var _this5 = this; var items = this.store.getItemsFilteredByActive(); items.forEach(function (item) { if (item.active && excludedId !== item.id) { _this5._removeItem(item); } }); return this; } /** * Remove all selected items from store * @note Removed items are soft deleted * @return {Object} Class instance * @public */ }, { key: 'removeHighlightedItems', value: function removeHighlightedItems() { var _this6 = this; var items = this.store.getItemsFilteredByActive(); items.forEach(function (item) { if (item.highlighted && item.active) { _this6._removeItem(item); } }); return this; } /** * Show dropdown to user by adding active state class * @return {Object} Class instance * @public */ }, { key: 'showDropdown', value: function showDropdown() { var focusInput = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; var body = document.body; var html = document.documentElement; var winHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); this.containerOuter.classList.add(this.config.classNames.openState); this.containerOuter.setAttribute('aria-expanded', 'true'); this.dropdown.classList.add(this.config.classNames.activeState); var dimensions = this.dropdown.getBoundingClientRect(); var dropdownPos = Math.ceil(dimensions.top + window.scrollY + dimensions.height); // If flip is enabled and the dropdown bottom position is greater than the window height flip the dropdown. var shouldFlip = this.config.flip ? dropdownPos >= winHeight : false; if (shouldFlip) { this.containerOuter.classList.add(this.config.classNames.flippedState); } else { this.containerOuter.classList.remove(this.config.classNames.flippedState); } // Optionally focus the input if we have a search input if (focusInput && this.canSearch && document.activeElement !== this.input) { this.input.focus(); } return this; } /** * Hide dropdown from user * @return {Object} Class instance * @public */ }, { key: 'hideDropdown', value: function hideDropdown() { var blurInput = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; // A dropdown flips if it does not have space within the page var isFlipped = this.containerOuter.classList.contains(this.config.classNames.flippedState); this.containerOuter.classList.remove(this.config.classNames.openState); this.containerOuter.setAttribute('aria-expanded', 'false'); this.dropdown.classList.remove(this.config.classNames.activeState); if (isFlipped) { this.containerOuter.classList.remove(this.config.classNames.flippedState); } // Optionally blur the input if we have a search input if (blurInput && this.canSearch && document.activeElement === this.input) { this.input.blur(); } return this; } /** * Determine whether to hide or show dropdown based on its current state * @return {Object} Class instance * @public */ }, { key: 'toggleDropdown', value: function toggleDropdown() { var hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState); if (hasActiveDropdown) { this.hideDropdown(); } else { this.showDropdown(true); } return this; } /** * Get value(s) of input (i.e. inputted items (text) or selected choices (select)) * @param {Boolean} valueOnly Get only values of selected items, otherwise return selected items * @return {Array/String} selected value (select-one) or array of selected items (inputs & select-multiple) * @public */ }, { key: 'getValue', value: function getValue() { var _this7 = this; var valueOnly = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; var items = this.store.getItemsFilteredByActive(); var selectedItems = []; items.forEach(function (item) { if (_this7.passedElement.type === 'text') { selectedItems.push(valueOnly ? item.value : item); } else if (item.active) { selectedItems.push(valueOnly ? item.value : item); } }); if (this.passedElement.type === 'select-one') { return selectedItems[0]; } return selectedItems; } /** * Set value of input. If the input is a select box, a choice will be created and selected otherwise * an item will created directly. * @param {Array} args Array of value objects or value strings * @return {Object} Class instance * @public */ }, { key: 'setValue', value: function setValue(args) { var _this8 = this; if (this.initialised === true) { // Convert args to an itterable array var values = [].concat(_toConsumableArray(args)); values.forEach(function (item) { if ((0, _utils.isType)('Object', item)) { if (!item.value) return; // If we are dealing with a select input, we need to create an option first // that is then selected. For text inputs we can just add items normally. if (_this8.passedElement.type !== 'text') { _this8._addChoice(true, false, item.value, item.label, -1); } else { _this8._addItem(item.value, item.label, item.id); } } else if ((0, _utils.isType)('String', item)) { if (_this8.passedElement.type !== 'text') { _this8._addChoice(true, false, item, item, -1); } else { _this8._addItem(item); } } }); } return this; } /** * Select value of select box via the value of an existing choice * @param {Array/String} value An array of strings of a single string * @return {Object} Class instance * @public */ }, { key: 'setValueByChoice', value: function setValueByChoice(value) { var _this9 = this; if (this.passedElement.type !== 'text') { (function () { var choices = _this9.store.getChoices(); // If only one value has been passed, convert to array var choiceValue = (0, _utils.isType)('Array', value) ? value : [value]; // Loop through each value and choiceValue.forEach(function (val) { var foundChoice = choices.find(function (choice) { // Check 'value' property exists and the choice isn't already selected return choice.value === val; }); if (foundChoice) { if (!foundChoice.selected) { _this9._addItem(foundChoice.value, foundChoice.label, foundChoice.id); } else { console.warn('Attempting to select choice already selected'); } } else { console.warn('Attempting to select choice that does not exist'); } }); })(); } return this; } /** * Direct populate choices * @param {Array} choices - Choices to insert * @param {String} value - Name of 'value' property * @param {String} label - Name of 'label' property * @return {Object} Class instance * @public */ }, { key: 'setChoices', value: function setChoices(choices, value, label) { var _this10 = this; if (this.initialised === true) { if (this.passedElement.type === 'select-one' || this.passedElement.type === 'select-multiple') { if (!(0, _utils.isType)('Array', choices) || !value) return; if (choices && choices.length) { this.containerOuter.classList.remove(this.config.classNames.loadingState); choices.forEach(function (result, index) { if (result.choices) { _this10._addGroup(result, index); } else { _this10._addChoice(result.selected ? result.selected : false, result.disabled ? result.disabled : false, result[value], result[label]); } }); } } } return this; } /** * Clear items,choices and groups * @note Hard delete * @return {Object} Class instance * @public */ }, { key: 'clearStore', value: function clearStore() { this.store.dispatch((0, _index3.clearAll)()); return this; } /** * Set value of input to blank * @return {Object} Class instance * @public */ }, { key: 'clearInput', value: function clearInput() { if (this.input.value) this.input.value = ''; if (this.passedElement.type !== 'select-one') { this.input.style.width = (0, _utils.getWidthOfInput)(this.input); } return this; } /** * Disable interaction with Choices * @return {Object} Class instance * @public */ }, { key: 'disable', value: function disable() { this.passedElement.disabled = true; if (this.initialised) { if (!this.containerOuter.classList.contains(this.config.classNames.disabledState)) { this._removeEventListeners(); this.passedElement.setAttribute('disabled', ''); this.input.setAttribute('disabled', ''); this.containerOuter.classList.add(this.config.classNames.disabledState); this.containerOuter.setAttribute('aria-disabled', 'true'); } } return this; } /** * Enable interaction with Choices * @return {Object} Class instance */ }, { key: 'enable', value: function enable() { this.passedElement.disabled = false; if (this.initialised) { if (this.containerOuter.classList.contains(this.config.classNames.disabledState)) { this._addEventListeners(); this.passedElement.removeAttribute('disabled'); this.input.removeAttribute('disabled'); this.containerOuter.classList.remove(this.config.classNames.disabledState); this.containerOuter.removeAttribute('aria-disabled'); } } return this; } /** * Populate options via ajax callback * @param {Function} fn Passed * @return {Object} Class instance * @public */ }, { key: 'ajax', value: function ajax(fn) { var _this11 = this; if (this.initialised === true) { if (this.passedElement.type === 'select-one' || this.passedElement.type === 'select-multiple') { this.containerOuter.classList.add(this.config.classNames.loadingState); this.containerOuter.setAttribute('aria-busy', 'true'); if (this.passedElement.type === 'select-one') { var placeholderItem = this._getTemplate('placeholder', this.config.loadingText); this.itemList.appendChild(placeholderItem); } else { this.input.placeholder = this.config.loadingText; } var callback = function callback(results, value, label) { if (!(0, _utils.isType)('Array', results) || !value) return; if (results && results.length) { // Remove loading states/text _this11.containerOuter.classList.remove(_this11.config.classNames.loadingState); if (_this11.passedElement.type === 'select-multiple') { var placeholder = _this11.config.placeholder ? _this11.config.placeholderValue || _this11.passedElement.getAttribute('placeholder') : false; if (placeholder) { _this11.input.placeholder = placeholder; } } // Add each result as a choice results.forEach(function (result, index) { // Select first choice in list if single select input if (index === 0 && _this11.passedElement.type === 'select-one') { _this11._addChoice(true, false, result[value], result[label]); } else { _this11._addChoice(false, false, result[value], result[label]); } }); } _this11.containerOuter.removeAttribute('aria-busy'); }; fn(callback); } } return this; } /** * Call change callback * @param {String} value - last added/deleted/selected value * @return * @private */ }, { key: '_triggerChange', value: function _triggerChange(value) { if (!value) return; // Run callback if it is a function if (this.config.callbackOnChange) { var callback = this.config.callbackOnChange; if ((0, _utils.isType)('Function', callback)) { callback(value, this.passedElement); } else { console.error('callbackOnChange: Callback is not a function'); } } // Keep focus on select-one element if (this.passedElement.type === 'select-one') { this.focusAndHideDropdown = true; this.containerOuter.focus(); } } /** * Process enter/click of an item button * @param {Array} activeItems The currently active items * @param {Element} element Button being interacted with * @return * @private */ }, { key: '_handleButtonAction', value: function _handleButtonAction(activeItems, element) { var _this12 = this; if (!activeItems || !element) return; // If we are clicking on a button if (this.config.removeItems && this.config.removeItemButton) { (function () { var itemId = element.parentNode.getAttribute('data-id'); var itemToRemove = activeItems.find(function (item) { return item.id === parseInt(itemId, 10); }); // Remove item associated with button _this12._removeItem(itemToRemove); _this12._triggerChange(itemToRemove.value); if (_this12.passedElement.type === 'select-one') { var placeholder = _this12.config.placeholder ? _this12.config.placeholderValue || _this12.passedElement.getAttribute('placeholder') : false; if (placeholder) { var placeholderItem = _this12._getTemplate('placeholder', placeholder); _this12.itemList.appendChild(placeholderItem); } } })(); } } /** * Process click of an item * @param {Array} activeItems The currently active items * @param {Element} element Item being interacted with * @param {Boolean} hasShiftKey Whether the user has the shift key active * @return * @private */ }, { key: '_handleItemAction', value: function _handleItemAction(activeItems, element) { var _this13 = this; var hasShiftKey = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; if (!activeItems || !element) return; // If we are clicking on an item if (this.config.removeItems && this.passedElement.type !== 'select-one') { (function () { var passedId = element.getAttribute('data-id'); // We only want to select one item with a click // so we deselect any items that aren't the target // unless shift is being pressed activeItems.forEach(function (item) { if (item.id === parseInt(passedId, 10) && !item.highlighted) { _this13.highlightItem(item); } else if (!hasShiftKey) { if (item.highlighted) { _this13.unhighlightItem(item); } } }); // Focus input as without focus, a user cannot do anything with a // highlighted item if (document.activeElement !== _this13.input) _this13.input.focus(); })(); } } /** * Process click of a choice * @param {Array} activeItems The currently active items * @param {Element} element Choice being interacted with * @return {[type]} [description] */ }, { key: '_handleChoiceAction', value: function _handleChoiceAction(activeItems, element) { if (!activeItems || !element) return; // If we are clicking on an option var id = element.getAttribute('data-id'); var choice = this.store.getChoiceById(id); var hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState); if (choice && !choice.selected && !choice.disabled) { var canAddItem = this._canAddItem(activeItems, choice.value); if (canAddItem.response) { this._addItem(choice.value, choice.label, choice.id); this._triggerChange(choice.value); this.clearInput(this.passedElement); this.isSearching = false; this.store.dispatch((0, _index3.activateChoices)(true)); // We only hide the dropdown on a choice selection for single select boxes if (this.passedElement.type === 'select-one' && hasActiveDropdown) { this.hideDropdown(); } } } } /** * Process back space event * @param {Array} Active items * @return * @private */ }, { key: '_handleBackspace', value: function _handleBackspace(activeItems) { if (this.config.removeItems && activeItems) { var lastItem = activeItems[activeItems.length - 1]; var hasHighlightedItems = activeItems.some(function (item) { return item.highlighted === true; }); // If editing the last item is allowed and there are not other selected items, // we can edit the item value. Otherwise if we can remove items, remove all selected items if (this.config.editItems && !hasHighlightedItems && lastItem) { this.input.value = lastItem.value; this._removeItem(lastItem); this._triggerChange(lastItem.value); } else { if (!hasHighlightedItems) { this.highlightItem(lastItem); } this.removeHighlightedItems(); } } } /** * Validates whether an item can be added by a user * @param {Array} activeItems The currently active items * @param {String} value Value of item to add * @return {Object} Response: Whether user can add item * Notice: Notice show in dropdown */ }, { key: '_canAddItem', value: function _canAddItem(activeItems, value) { var canAddItem = true; var notice = 'Press Enter to add "' + value + '"'; if (this.passedElement.type === 'select-multiple' || this.passedElement.type === 'text') { if (this.config.maxItemCount > 0 && this.config.maxItemCount <= this.itemList.children.length) { // If there is a max entry limit and we have reached that limit // don't update canAddItem = false; notice = 'Only ' + this.config.maxItemCount + ' values can be added.'; } } if (this.passedElement.type === 'text' && this.config.addItems) { var isUnique = !activeItems.some(function (item) { return item.value === value; }); // If a user has supplied a regular expression filter if (this.config.regexFilter) { // Determine whether we can update based on whether // our regular expression passes canAddItem = this._regexFilter(value); } // If no duplicates are allowed, and the value already exists // in the array if (this.config.duplicateItems === false && !isUnique) { canAddItem = false; notice = 'Only unique values can be added.'; } } return { response: canAddItem, notice: notice }; } /** * Filter choices based on search value * @param {String} value Value to filter by * @return * @private */ }, { key: '_searchChoices', value: function _searchChoices(value) { var _this14 = this; if (!value) return; if (this.input === document.activeElement) { var choices = this.store.getChoices(); var hasUnactiveChoices = choices.some(function (option) { return option.active !== true; }); // Check that we have a value to search and the input was an alphanumeric character if (value && value.length > 1) { var handleFilter = function handleFilter() { var newValue = (0, _utils.isType)('String', value) ? value.trim() : value; var currentValue = (0, _utils.isType)('String', _this14.currentValue) ? _this14.currentValue.trim() : _this14.currentValue; if (newValue.length >= 1 && newValue !== currentValue + ' ') { var haystack = _this14.store.getChoicesFilteredBySelectable(); var needle = newValue; var keys = (0, _utils.isType)('Array', _this14.config.sortFields) ? _this14.config.sortFields : [_this14.config.sortFields]; var fuse = new _fuse2.default(haystack, { keys: keys, shouldSort: true, include: 'score' }); var results = fuse.search(needle); _this14.currentValue = newValue; _this14.highlightPosition = 0; _this14.isSearching = true; _this14.store.dispatch((0, _index3.filterChoices)(results)); } }; handleFilter(); } else if (hasUnactiveChoices) { // Otherwise reset choices to active this.isSearching = false; this.store.dispatch((0, _index3.activateChoices)(true)); } } } /** * Trigger event listeners * @return * @private */ }, { key: '_addEventListeners', value: function _addEventListeners() { document.addEventListener('keyup', this._onKeyUp); document.addEventListener('keydown', this._onKeyDown); document.addEventListener('click', this._onClick); document.addEventListener('touchmove', this._onTouchMove); document.addEventListener('touchend', this._onTouchEnd); document.addEventListener('mousedown', this._onMouseDown); document.addEventListener('mouseover', this._onMouseOver); if (this.passedElement.type && this.passedElement.type === 'select-one') { this.containerOuter.addEventListener('focus', this._onFocus); this.containerOuter.addEventListener('blur', this._onBlur); } this.input.addEventListener('input', this._onInput); this.input.addEventListener('paste', this._onPaste); this.input.addEventListener('focus', this._onFocus); this.input.addEventListener('blur', this._onBlur); } /** * Destroy event listeners * @return * @private */ }, { key: '_removeEventListeners', value: function _removeEventListeners() { document.removeEventListener('keyup', this._onKeyUp); document.removeEventListener('keydown', this._onKeyDown); document.removeEventListener('click', this._onClick); document.removeEventListener('touchmove', this._onTouchMove); document.removeEventListener('touchend', this._onTouchEnd); document.removeEventListener('mousedown', this._onMouseDown); document.removeEventListener('mouseover', this._onMouseOver); if (this.passedElement.type && this.passedElement.type === 'select-one') { this.containerOuter.removeEventListener('focus', this._onFocus); this.containerOuter.removeEventListener('blur', this._onBlur); } this.input.removeEventListener('input', this._onInput); this.input.removeEventListener('paste', this._onPaste); this.input.removeEventListener('focus', this._onFocus); this.input.removeEventListener('blur', this._onBlur); } /** * Key down event * @param {Object} e Event * @return */ }, { key: '_onKeyDown', value: function _onKeyDown(e) { if (e.target !== this.input && !this.containerOuter.contains(e.target)) return; var target = e.target; var ctrlDownKey = e.ctrlKey || e.metaKey; var backKey = 46; var deleteKey = 8; var enterKey = 13; var aKey = 65; var escapeKey = 27; var upKey = 38; var downKey = 40; var activeItems = this.store.getItemsFilteredByActive(); var hasFocusedInput = this.input === document.activeElement; var hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState); var hasItems = this.itemList && this.itemList.children; var keyString = String.fromCharCode(e.keyCode); // If a user is typing and the dropdown is not active if (this.passedElement.type !== 'text' && /[a-zA-Z0-9-_ ]/.test(keyString) && !hasActiveDropdown) { this.showDropdown(); } this.canSearch = this.config.search; switch (e.keyCode) { case aKey: // If CTRL + A or CMD + A have been pressed and there are items to select if (ctrlDownKey && hasItems) { this.canSearch = false; if (this.config.removeItems && !this.input.value && this.input === document.activeElement) { // Highlight items this.highlightAll(this.itemList.children); } } break; case enterKey: // If enter key is pressed and the input has a value if (this.passedElement.type === 'text' && target.value) { var value = this.input.value; var canAddItem = this._canAddItem(activeItems, value); // All is good, add if (canAddItem.response) { if (hasActiveDropdown) { this.hideDropdown(); } this._addItem(value); this._triggerChange(value); this.clearInput(this.passedElement); } } if (target.hasAttribute('data-button')) { this._handleButtonAction(activeItems, target); e.preventDefault(); } if (hasActiveDropdown) { var highlighted = this.dropdown.querySelector('.' + this.config.classNames.highlightedState); if (highlighted) { this._handleChoiceAction(activeItems, highlighted); } // We always want to hide the dropdown for single selects // regardless of whether an item was added if (hasActiveDropdown && this.passedElement.type === 'select-one') { this.hideDropdown(); } } else if (this.passedElement.type === 'select-one') { // Open single select dropdown if it's not active if (!hasActiveDropdown) { this.showDropdown(true); e.preventDefault(); } } break; case escapeKey: if (hasActiveDropdown) this.toggleDropdown(); break; case downKey: case upKey: // If up or down key is pressed, traverse through options if (hasActiveDropdown || this.passedElement.type === 'select-one') { // Show dropdown if focus if (!hasActiveDropdown) { this.showDropdown(true); } var currentEl = this.dropdown.querySelector('.' + this.config.classNames.highlightedState); var directionInt = e.keyCode === downKey ? 1 : -1; var nextEl = void 0; this.canSearch = false; if (currentEl) { nextEl = (0, _utils.getAdjacentEl)(currentEl, '[data-choice-selectable]', directionInt); } else { nextEl = this.dropdown.querySelector('[data-choice-selectable]'); } if (nextEl) { // We prevent default to stop the cursor moving // when pressing the arrow if (!(0, _utils.isScrolledIntoView)(nextEl, this.choiceList, directionInt)) { this._scrollToChoice(nextEl, directionInt); } this._highlightChoice(nextEl); } // Prevent default to maintain cursor position whilst // traversing dropdown options e.preventDefault(); } break; case backKey: case deleteKey: // If backspace or delete key is pressed and the input has no value if (hasFocusedInput && !e.target.value && this.passedElement.type !== 'select-one') { this._handleBackspace(activeItems); e.preventDefault(); } break; default: break; } } /** * Key up event * @param {Object} e Event * @return * @private */ }, { key: '_onKeyUp', value: function _onKeyUp(e) { if (e.target !== this.input) return; // We are typing into a text input and have a value, we want to show a dropdown // notice. Otherwise hide the dropdown if (this.passedElement.type === 'text') { var hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState); var value = this.input.value; if (value) { var activeItems = this.store.getItemsFilteredByActive(); var canAddItem = this._canAddItem(activeItems, value); if (canAddItem.notice) { var dropdownItem = this._getTemplate('notice', canAddItem.notice); this.dropdown.innerHTML = dropdownItem.outerHTML; } if (canAddItem.response === true) { if (!hasActiveDropdown) { this.showDropdown(); } } else if (!canAddItem.notice && hasActiveDropdown) { this.hideDropdown(); } } else if (hasActiveDropdown) { this.hideDropdown(); } } else { var backKey = 46; var deleteKey = 8; // If user has removed value... if ((e.keyCode === backKey || e.keyCode === deleteKey) && !e.target.value) { // ...and it is a multiple select input, activate choices (if searching) if (this.passedElement.type !== 'text' && this.isSearching) { this.isSearching = false; this.store.dispatch((0, _index3.activateChoices)(true)); } } else if (this.canSearch) { this._searchChoices(this.input.value); } } } /** * Input event * @param {Object} e Event * @return * @private */ }, { key: '_onInput', value: function _onInput() { if (this.passedElement.type !== 'select-one') { if (this.config.placeholder && (this.config.placeholderValue || this.passedElement.getAttribute('placeholder'))) { // If there is a placeholder, we only want to set the width of the input when it is a greater // length than 75% of the placeholder. This stops the input jumping around. var placeholder = this.config.placeholder ? this.config.placeholderValue || this.passedElement.getAttribute('placeholder') : false; if (this.input.value && this.input.value.length >= placeholder.length / 1.25) { this.input.style.width = (0, _utils.getWidthOfInput)(this.input); } } else { // If there is no placeholder, resize input to contents this.input.style.width = (0, _utils.getWidthOfInput)(this.input); } } } /** * Touch move event * @param {Object} e Event * @return * @private */ }, { key: '_onTouchMove', value: function _onTouchMove() { if (this.wasTap === true) { this.wasTap = false; } } /** * Touch end event * @param {Object} e Event * @return * @private */ }, { key: '_onTouchEnd', value: function _onTouchEnd(e) { var target = e.target || e.touches[0].target; var hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState); // If a user tapped within our container... if (this.wasTap === true && this.containerOuter.contains(target)) { // ...and we aren't dealing with a single select box, show dropdown/focus input if ((target === this.containerOuter || target === this.containerInner) && this.passedElement.type !== 'select-one') { if (this.passedElement.type === 'text') { // If text element, we only want to focus the input (if it isn't already) if (document.activeElement !== this.input) { this.input.focus(); } } else { if (!hasActiveDropdown) { // If a select box, we want to show the dropdown this.showDropdown(true); } } } // Prevents focus event firing e.stopPropagation(); } this.wasTap = true; } /** * Mouse down event * @param {Object} e Event * @return * @private */ }, { key: '_onMouseDown', value: function _onMouseDown(e) { var target = e.target; if (this.containerOuter.contains(target) && target !== this.input) { var activeItems = this.store.getItemsFilteredByActive(); var hasShiftKey = e.shiftKey; if (target.hasAttribute('data-item')) { this._handleItemAction(activeItems, target, hasShiftKey); } else if (target.hasAttribute('data-choice')) { this._handleChoiceAction(activeItems, target); } e.preventDefault(); } } /** * Click event * @param {Object} e Event * @return * @private */ }, { key: '_onClick', value: function _onClick(e) { var target = e.target; var hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState); var activeItems = this.store.getItemsFilteredByActive(); // If target is something that concerns us if (this.containerOuter.contains(target)) { // Handle button delete if (target.hasAttribute('data-button')) { this._handleButtonAction(activeItems, target); } if (!hasActiveDropdown) { if (this.passedElement.type === 'text') { if (document.activeElement !== this.input) { this.input.focus(); } } else { if (this.canSearch) { this.showDropdown(true); } else { this.showDropdown(); this.containerOuter.focus(); } } } else if (this.passedElement.type === 'select-one' && target !== this.input && !this.dropdown.contains(target)) { this.hideDropdown(true); } } else { var hasHighlightedItems = activeItems.some(function (item) { return item.highlighted === true; }); // De-select any highlighted items if (hasHighlightedItems) { this.unhighlightAll(); } // Remove focus state this.containerOuter.classList.remove(this.config.classNames.focusState); // Close all other dropdowns if (hasActiveDropdown) { this.hideDropdown(); } } } /** * Mouse over (hover) event * @param {Object} e Event * @return * @private */ }, { key: '_onMouseOver', value: function _onMouseOver(e) { // If the dropdown is either the target or one of its children is the target if (e.target === this.dropdown || this.dropdown.contains(e.target)) { if (e.target.hasAttribute('data-choice')) this._highlightChoice(e.target); } } /** * Paste event * @param {Object} e Event * @return * @private */ }, { key: '_onPaste', value: function _onPaste(e) { // Disable pasting into the input if option has been set if (e.target === this.input && !this.config.paste) { e.preventDefault(); } } /** * Focus event * @param {Object} e Event * @return * @private */ }, { key: '_onFocus', value: function _onFocus(e) { var target = e.target; // If target is something that concerns us if (this.containerOuter.contains(target)) { var hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState); switch (this.passedElement.type) { case 'text': { if (target === this.input) { this.containerOuter.classList.add(this.config.classNames.focusState); } break; } case 'select-one': { if (target === this.containerOuter) { // If element is a select box, the focussed element is the container and the dropdown // isn't already open, focus and show dropdown this.containerOuter.classList.add(this.config.classNames.focusState); // Show dropdown if it isn't already showing if (!hasActiveDropdown) { if (!this.focusAndHideDropdown && this.canSearch && document.activeElement !== this.input) { this.showDropdown(true); } else { this.showDropdown(); } } this.focusAndHideDropdown = false; } if (target === this.input) { // If element is a select box, the focussed element is the container and the dropdown // isn't already open, focus and show dropdown this.containerOuter.classList.add(this.config.classNames.focusState); // Show dropdown if it isn't already showing if (!hasActiveDropdown) { this.showDropdown(); } } break; } case 'select-multiple': { if (target === this.input) { // If element is a select box, the focussed element is the container and the dropdown // isn't already open, focus and show dropdown this.containerOuter.classList.add(this.config.classNames.focusState); if (!hasActiveDropdown) { this.showDropdown(true); } } break; } default: break; } } } /** * Blur event * @param {Object} e Event * @return * @private */ }, { key: '_onBlur', value: function _onBlur(e) { var target = e.target; // If target is something that concerns us if (this.containerOuter.contains(target)) { var activeItems = this.store.getItemsFilteredByActive(); var hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState); var hasHighlightedItems = activeItems.some(function (item) { return item.highlighted === true; }); switch (this.passedElement.type) { case 'text': { if (target === this.input) { // Remove the focus state this.containerOuter.classList.remove(this.config.classNames.focusState); // De-select any highlighted items if (hasHighlightedItems) { this.unhighlightAll(); } // Hide dropdown if it is showing if (hasActiveDropdown) { this.hideDropdown(); } } break; } case 'select-one': { if (target === this.containerOuter) { this.containerOuter.classList.remove(this.config.classNames.focusState); // Hide dropdown if it is showing if (hasActiveDropdown && !this.canSearch) { this.hideDropdown(); } } if (target === this.input) { this.containerOuter.classList.remove(this.config.classNames.focusState); // Hide dropdown if it is showing if (hasActiveDropdown) { this.hideDropdown(); } } break; } case 'select-multiple': { if (target === this.input) { // Remove the focus state this.containerOuter.classList.remove(this.config.classNames.focusState); if (hasActiveDropdown) { this.hideDropdown(); } // De-select any highlighted items if (hasHighlightedItems) { this.unhighlightAll(); } } break; } default: break; } } } /** * Tests value against a regular expression * @param {string} value Value to test * @return {Boolean} Whether test passed/failed * @private */ }, { key: '_regexFilter', value: function _regexFilter(value) { if (!value) return; var regex = this.config.regexFilter; var expression = new RegExp(regex.source, 'i'); return expression.test(value); } /** * Scroll to an option element * @param {HTMLElement} option Option to scroll to * @param {Number} direction Whether option is above or below * @return * @private */ }, { key: '_scrollToChoice', value: function _scrollToChoice(choice, direction) { var _this15 = this; if (!choice) return; var dropdownHeight = this.choiceList.offsetHeight; var choiceHeight = choice.offsetHeight; // Distance from bottom of element to top of parent var choicePos = choice.offsetTop + choiceHeight; // Scroll position of dropdown var containerScrollPos = this.choiceList.scrollTop + dropdownHeight; // Difference between the choice and scroll position var endPoint = direction > 0 ? this.choiceList.scrollTop + choicePos - containerScrollPos : choice.offsetTop; var animateScroll = function animateScroll() { var strength = 4; var continueAnimation = false; var easing = void 0; var distance = void 0; if (direction > 0) { easing = (endPoint - _this15.choiceList.scrollTop) / strength; distance = easing > 1 ? easing : 1; _this15.choiceList.scrollTop = _this15.choiceList.scrollTop + distance; if (_this15.choiceList.scrollTop < endPoint) { continueAnimation = true; } } else { easing = (_this15.choiceList.scrollTop - endPoint) / strength; distance = easing > 1 ? easing : 1; _this15.choiceList.scrollTop = _this15.choiceList.scrollTop - distance; if (_this15.choiceList.scrollTop > endPoint) { continueAnimation = true; } } if (continueAnimation) { requestAnimationFrame(function (time) { animateScroll(time, endPoint, direction); }); } }; requestAnimationFrame(function (time) { animateScroll(time, endPoint, direction); }); } /** * Highlight choice * @param {HTMLElement} el Element to highlight * @return * @private */ }, { key: '_highlightChoice', value: function _highlightChoice(el) { var _this16 = this; // Highlight first element in dropdown var choices = Array.from(this.dropdown.querySelectorAll('[data-choice-selectable]')); if (choices && choices.length) { var highlightedChoices = Array.from(this.dropdown.querySelectorAll('.' + this.config.classNames.highlightedState)); // Remove any highlighted choices highlightedChoices.forEach(function (choice) { choice.classList.remove(_this16.config.classNames.highlightedState); choice.setAttribute('aria-selected', 'false'); }); if (el) { // Highlight given option el.classList.add(this.config.classNames.highlightedState); this.highlightPosition = choices.indexOf(el); } else { // Highlight choice based on last known highlight location var choice = void 0; if (choices.length > this.highlightPosition) { // If we have an option to highlight choice = choices[this.highlightPosition]; } else { // Otherwise highlight the option before choice = choices[choices.length - 1]; } if (!choice) choice = choices[0]; choice.classList.add(this.config.classNames.highlightedState); choice.setAttribute('aria-selected', 'true'); } } } /** * Add item to store with correct value * @param {String} value Value to add to store * @param {String} label Label to add to store * @return {Object} Class instance * @public */ }, { key: '_addItem', value: function _addItem(value, label) { var choiceId = arguments.length <= 2 || arguments[2] === undefined ? -1 : arguments[2]; var passedValue = (0, _utils.isType)('String', value) ? value.trim() : value; var items = this.store.getItems(); var passedLabel = label || passedValue; var passedOptionId = parseInt(choiceId, 10) || -1; // If a prepended value has been passed, prepend it if (this.config.prependValue) { passedValue = this.config.prependValue + passedValue.toString(); } // If an appended value has been passed, append it if (this.config.appendValue) { passedValue += this.config.appendValue.toString(); } // Generate unique id var id = items ? items.length + 1 : 1; this.store.dispatch((0, _index3.addItem)(passedValue, passedLabel, id, passedOptionId)); if (this.passedElement.type === 'select-one') { this.removeActiveItems(id); } // Run callback if it is a function if (this.config.callbackOnAddItem) { var callback = this.config.callbackOnAddItem; if ((0, _utils.isType)('Function', callback)) { callback(id, passedValue, this.passedElement); } else { console.error('callbackOnAddItem: Callback is not a function'); } } return this; } /** * Remove item from store * @param {Object} item Item to remove * @param {Function} callback Callback to trigger * @return {Object} Class instance * @public */ }, { key: '_removeItem', value: function _removeItem(item) { var callback = arguments.length <= 1 || arguments[1] === undefined ? this.config.callbackOnRemoveItem : arguments[1]; if (!item || !(0, _utils.isType)('Object', item)) { console.error('removeItem: No item object was passed to be removed'); return; } var id = item.id; var value = item.value; var choiceId = item.choiceId; this.store.dispatch((0, _index3.removeItem)(id, choiceId)); // Run callback if (callback) { if (!(0, _utils.isType)('Function', callback)) { console.error('callbackOnRemoveItem: Callback is not a function'); return; } callback(id, value, this.passedElement); } return this; } /** * Add choice to dropdown * @param {Boolean} isSelected Whether choice is selected * @param {Boolean} isDisabled Whether choice is disabled * @param {String} value Value of choice * @param {String} Label Label of choice * @param {Number} groupId ID of group choice is within. Negative number indicates no group * @return * @private */ }, { key: '_addChoice', value: function _addChoice(isSelected, isDisabled, value, label) { var groupId = arguments.length <= 4 || arguments[4] === undefined ? -1 : arguments[4]; if (!value) return; // Generate unique id var choices = this.store.getChoices(); var choiceLabel = label || value; var choiceId = choices ? choices.length + 1 : 1; this.store.dispatch((0, _index3.addChoice)(value, choiceLabel, choiceId, groupId, isDisabled)); if (isSelected && !isDisabled) { this._addItem(value, choiceLabel, choiceId); } } /** * Add group to dropdown * @param {Object} group Group to add * @param {Number} id Group ID * @return * @private */ }, { key: '_addGroup', value: function _addGroup(group, id) { var _this17 = this; var groupChoices = (0, _utils.isType)('Object', group) ? group.choices : Array.from(group.getElementsByTagName('OPTION')); var groupId = id; var isDisabled = group.disabled ? group.disabled : false; if (groupChoices) { this.store.dispatch((0, _index3.addGroup)(group.label, groupId, true, isDisabled)); groupChoices.forEach(function (option) { var isOptDisabled = option.disabled || option.parentNode && option.parentNode.disabled || false; var isOptSelected = option.selected ? option.selected : false; var label = void 0; if ((0, _utils.isType)('Object', option)) { label = option.label || option.value; } else { label = option.innerHTML; } _this17._addChoice(isOptSelected, isOptDisabled, option.value, label, groupId); }); } else { this.store.dispatch((0, _index3.addGroup)(group.label, group.id, false, group.disabled)); } } /** * Get template from name * @param {String} template Name of template to get * @param {...} args Data to pass to template * @return {HTMLElement} Template * @private */ }, { key: '_getTemplate', value: function _getTemplate(template) { if (!template) return; var templates = this.config.templates; for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return templates[template].apply(templates, args); } /** * Create HTML element based on type and arguments * @return * @private */ }, { key: '_createTemplates', value: function _createTemplates() { var _this18 = this; var classNames = this.config.classNames; var templates = { containerOuter: function containerOuter() { return (0, _utils.strToEl)('\n <div class="' + classNames.containerOuter + '" data-type="' + _this18.passedElement.type + '" ' + (_this18.passedElement.type === 'select-one' ? 'tabindex="0"' : '') + ' aria-haspopup="true" aria-expanded="false"></div>\n '); }, containerInner: function containerInner() { return (0, _utils.strToEl)('\n <div class="' + classNames.containerInner + '"></div>\n '); }, itemList: function itemList() { return (0, _utils.strToEl)('\n <div class="' + classNames.list + ' ' + (_this18.passedElement.type === 'select-one' ? classNames.listSingle : classNames.listItems) + '"></div>\n '); }, placeholder: function placeholder(value) { return (0, _utils.strToEl)('\n <div class="' + classNames.placeholder + '">\n ' + value + '\n </div>\n '); }, item: function item(data) { if (_this18.config.removeItemButton) { return (0, _utils.strToEl)('\n <div class="' + classNames.item + ' ' + (data.highlighted ? classNames.highlightedState : '') + ' ' + (!data.disabled ? classNames.itemSelectable : '') + '" data-item data-id="' + data.id + '" data-value="' + data.value + '" ' + (data.active ? 'aria-selected="true"' : '') + ' ' + (data.disabled ? 'aria-disabled="true"' : '') + ' data-deletable>\n ' + data.label + '<button class="' + classNames.button + '" data-button>Remove item</button>\n </div>\n '); } return (0, _utils.strToEl)('\n <div class="' + classNames.item + ' ' + (data.highlighted ? classNames.highlightedState : classNames.itemSelectable) + '" data-item data-id="' + data.id + '" data-value="' + data.value + '" ' + (data.active ? 'aria-selected="true"' : '') + ' ' + (data.disabled ? 'aria-disabled="true"' : '') + '>\n ' + data.label + '\n </div>\n '); }, choiceList: function choiceList() { return (0, _utils.strToEl)('\n <div class="' + classNames.list + '" dir="ltr" role="listbox" ' + (_this18.passedElement.type !== 'select-one' ? 'aria-multiselectable="true"' : '') + '></div>\n '); }, choiceGroup: function choiceGroup(data) { return (0, _utils.strToEl)('\n <div class="' + classNames.group + ' ' + (data.disabled ? classNames.itemDisabled : '') + '" data-group data-id="' + data.id + '" data-value="' + data.value + '" role="group" ' + (data.disabled ? 'aria-disabled="true"' : '') + '>\n <div class="' + classNames.groupHeading + '">' + data.value + '</div>\n </div>\n '); }, choice: function choice(data) { return (0, _utils.strToEl)('\n <div class="' + classNames.item + ' ' + classNames.itemChoice + ' ' + (data.disabled ? classNames.itemDisabled : classNames.itemSelectable) + '" data-choice ' + (data.disabled ? 'data-choice-disabled aria-disabled="true"' : 'data-choice-selectable') + ' data-id="' + data.id + '" data-value="' + data.value + '" ' + (data.groupId > 0 ? 'role="treeitem"' : 'role="option"') + '>\n ' + data.label + '\n </div>\n '); }, input: function input() { return (0, _utils.strToEl)('\n <input type="text" class="' + classNames.input + ' ' + classNames.inputCloned + '" autocomplete="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list">\n '); }, dropdown: function dropdown() { return (0, _utils.strToEl)('\n <div class="' + classNames.list + ' ' + classNames.listDropdown + '" aria-expanded="false"></div>\n '); }, notice: function notice(label) { return (0, _utils.strToEl)('\n <div class="' + classNames.item + ' ' + classNames.itemChoice + '">' + label + '</div>\n '); }, option: function option(data) { return (0, _utils.strToEl)('\n <option value="' + data.value + '" selected>' + data.label + '</option>\n '); } }; this.config.templates = templates; } /** * Create DOM structure around passed select element * @return * @private */ }, { key: '_createInput', value: function _createInput() { var _this19 = this; var containerOuter = this._getTemplate('containerOuter'); var containerInner = this._getTemplate('containerInner'); var itemList = this._getTemplate('itemList'); var choiceList = this._getTemplate('choiceList'); var input = this._getTemplate('input'); var dropdown = this._getTemplate('dropdown'); this.containerOuter = containerOuter; this.containerInner = containerInner; this.input = input; this.choiceList = choiceList; this.itemList = itemList; this.dropdown = dropdown; // Hide passed input this.passedElement.classList.add(this.config.classNames.input, this.config.classNames.hiddenState); this.passedElement.tabIndex = '-1'; this.passedElement.setAttribute('style', 'display:none;'); this.passedElement.setAttribute('aria-hidden', 'true'); this.passedElement.setAttribute('data-choice', 'active'); // Wrap input in container preserving DOM ordering (0, _utils.wrap)(this.passedElement, containerInner); // Wrapper inner container with outer container (0, _utils.wrap)(containerInner, containerOuter); // If placeholder has been enabled and we have a value var placeholder = this.config.placeholder ? this.config.placeholderValue || this.passedElement.getAttribute('placeholder') : false; if (placeholder) { input.placeholder = placeholder; if (this.passedElement.type !== 'select-one') { input.style.width = (0, _utils.getWidthOfInput)(input); } } if (!this.config.addItems) this.disable(); containerOuter.appendChild(containerInner); containerOuter.appendChild(dropdown); containerInner.appendChild(itemList); if (this.passedElement.type !== 'text') { dropdown.appendChild(choiceList); } if (this.passedElement.type === 'select-multiple' || this.passedElement.type === 'text') { containerInner.appendChild(input); } else if (this.canSearch) { dropdown.insertBefore(input, dropdown.firstChild); } if (this.passedElement.type === 'select-multiple' || this.passedElement.type === 'select-one') { var passedGroups = Array.from(this.passedElement.getElementsByTagName('OPTGROUP')); this.highlightPosition = 0; this.isSearching = false; if (passedGroups && passedGroups.length) { passedGroups.forEach(function (group, index) { _this19._addGroup(group, index); }); } else { (function () { var passedOptions = Array.from(_this19.passedElement.options); var allChoices = []; // Create array of options from option elements passedOptions.forEach(function (o) { allChoices.push({ value: o.value, label: o.innerHTML, selected: o.selected, disabled: o.disabled || o.parentNode.disabled }); }); // Join choices with preset choices and add them allChoices.concat(_this19.presetChoices).forEach(function (o, index) { if (index === 0 && _this19.passedElement.type === 'select-one') { _this19._addChoice(true, o.disabled ? o.disabled : false, o.value, o.label); } else { _this19._addChoice(o.selected ? o.selected : false, o.disabled ? o.disabled : false, o.value, o.label); } }); })(); } } else if (this.passedElement.type === 'text') { // Add any preset values seperated by delimiter this.presetItems.forEach(function (item) { if ((0, _utils.isType)('Object', item)) { if (!item.value) return; _this19._addItem(item.value, item.label, item.id); } else if ((0, _utils.isType)('String', item)) { _this19._addItem(item); } }); } } /** * Render group choices into a DOM fragment and append to choice list * @param {Array} groups Groups to add to list * @param {Array} choices Choices to add to groups * @param {DocumentFragment} fragment Fragment to add groups and options to (optional) * @return {DocumentFragment} Populated options fragment * @private */ }, { key: 'renderGroups', value: function renderGroups(groups, choices, fragment) { var _this20 = this; var groupFragment = fragment || document.createDocumentFragment(); var filter = this.config.sortFilter; groups.sort(filter).forEach(function (group) { // Grab options that are children of this group var groupChoices = choices.filter(function (choice) { if (_this20.passedElement.type === 'select-one') { return choice.groupId === group.id; } return choice.groupId === group.id && !choice.selected; }); if (groupChoices.length >= 1) { var dropdownGroup = _this20._getTemplate('choiceGroup', group); groupFragment.appendChild(dropdownGroup); _this20.renderChoices(groupChoices, groupFragment); } }); return groupFragment; } /** * Render choices into a DOM fragment and append to choice list * @param {Array} choices Choices to add to list * @param {DocumentFragment} fragment Fragment to add choices to (optional) * @return {DocumentFragment} Populated choices fragment * @private */ }, { key: 'renderChoices', value: function renderChoices(choices, fragment) { var _this21 = this; // Create a fragment to store our list items (so we don't have to update the DOM for each item) var choicesFragment = fragment || document.createDocumentFragment(); var filter = this.isSearching ? _utils.sortByScore : this.config.sortFilter; choices.sort(filter).forEach(function (choice) { var dropdownItem = _this21._getTemplate('choice', choice); if (_this21.passedElement.type === 'select-one') { choicesFragment.appendChild(dropdownItem); } else if (!choice.selected) { choicesFragment.appendChild(dropdownItem); } }); return choicesFragment; } /** * Render items into a DOM fragment and append to items list * @param {Array} items Items to add to list * @param {DocumentFragment} fragment Fragrment to add items to (optional) * @return * @private */ }, { key: 'renderItems', value: function renderItems(items, fragment) { var _this22 = this; // Create fragment to add elements to var itemListFragment = fragment || document.createDocumentFragment(); // Simplify store data to just values var itemsFiltered = this.store.getItemsReducedToValues(items); if (this.passedElement.type === 'text') { // Assign hidden input array of values this.passedElement.setAttribute('value', itemsFiltered.join(this.config.delimiter)); } else { (function () { var selectedOptionsFragment = document.createDocumentFragment(); // Add each list item to list items.forEach(function (item) { // Create a standard select option var option = _this22._getTemplate('option', item); // Append it to fragment selectedOptionsFragment.appendChild(option); }); // Update selected choices _this22.passedElement.innerHTML = ''; _this22.passedElement.appendChild(selectedOptionsFragment); })(); } // Add each list item to list items.forEach(function (item) { // Create new list element var listItem = _this22._getTemplate('item', item); // Append it to list itemListFragment.appendChild(listItem); }); return itemListFragment; } /** * Render DOM with values * @return * @private */ }, { key: 'render', value: function render() { this.currentState = this.store.getState(); // Only render if our state has actually changed if (this.currentState !== this.prevState) { // Choices if (this.currentState.choices !== this.prevState.choices || this.currentState.groups !== this.prevState.groups) { if (this.passedElement.type === 'select-multiple' || this.passedElement.type === 'select-one') { // Get active groups/choices var activeGroups = this.store.getGroupsFilteredByActive(); var activeChoices = this.store.getChoicesFilteredByActive(); var choiceListFragment = document.createDocumentFragment(); // Clear choices this.choiceList.innerHTML = ''; // Scroll back to top of choices list this.choiceList.scrollTop = 0; // If we have grouped options if (activeGroups.length >= 1 && this.isSearching !== true) { choiceListFragment = this.renderGroups(activeGroups, activeChoices, choiceListFragment); } else if (activeChoices.length >= 1) { choiceListFragment = this.renderChoices(activeChoices, choiceListFragment); } if (choiceListFragment.childNodes && choiceListFragment.childNodes.length > 0) { // If we actually have anything to add to our dropdown // append it and highlight the first choice this.choiceList.appendChild(choiceListFragment); this._highlightChoice(); } else { // Otherwise show a notice var dropdownItem = this.isSearching ? this._getTemplate('notice', this.config.noResultsText) : this._getTemplate('notice', this.config.noChoicesText); this.choiceList.appendChild(dropdownItem); } } } // Items if (this.currentState.items !== this.prevState.items) { var activeItems = this.store.getItemsFilteredByActive(); if (activeItems) { // Create a fragment to store our list items // (so we don't have to update the DOM for each item) var itemListFragment = this.renderItems(activeItems); // Clear list this.itemList.innerHTML = ''; // If we have items to add if (itemListFragment.childNodes) { // Update list this.itemList.appendChild(itemListFragment); } } } this.prevState = this.currentState; } } }]); return Choices; }(); exports.default = Choices; window.Choices = module.exports = Choices; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /** * @license * Fuse - Lightweight fuzzy-search * * Copyright (c) 2012-2016 Kirollos Risk <kirollos@gmail.com>. * All Rights Reserved. Apache Software License 2.0 * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ;(function (global) { 'use strict' function log () { console.log.apply(console, arguments) } var defaultOptions = { // The name of the identifier property. If specified, the returned result will be a list // of the items' dentifiers, otherwise it will be a list of the items. id: null, // Indicates whether comparisons should be case sensitive. caseSensitive: false, // An array of values that should be included from the searcher's output. When this array // contains elements, each result in the list will be of the form `{ item: ..., include1: ..., include2: ... }`. // Values you can include are `score`, `matchedLocations` include: [], // Whether to sort the result list, by score shouldSort: true, // The search function to use // Note that the default search function ([[Function]]) must conform to the following API: // // @param pattern The pattern string to search // @param options The search option // [[Function]].constructor = function(pattern, options) // // @param text: the string to search in for the pattern // @return Object in the form of: // - isMatch: boolean // - score: Int // [[Function]].prototype.search = function(text) searchFn: BitapSearcher, // Default sort function sortFn: function (a, b) { return a.score - b.score }, // The get function to use when fetching an object's properties. // The default will search nested paths *ie foo.bar.baz* getFn: deepValue, // List of properties that will be searched. This also supports nested properties. keys: [], // Will print to the console. Useful for debugging. verbose: false, // When true, the search algorithm will search individual words **and** the full string, // computing the final score as a function of both. Note that when `tokenize` is `true`, // the `threshold`, `distance`, and `location` are inconsequential for individual tokens. tokenize: false, // Regex used to separate words when searching. Only applicable when `tokenize` is `true`. tokenSeparator: / +/g } function Fuse (list, options) { var i var len var key var keys this.list = list this.options = options = options || {} // Add boolean type options for (i = 0, keys = ['sort', 'shouldSort', 'verbose', 'tokenize'], len = keys.length; i < len; i++) { key = keys[i] this.options[key] = key in options ? options[key] : defaultOptions[key] } // Add all other options for (i = 0, keys = ['searchFn', 'sortFn', 'keys', 'getFn', 'include', 'tokenSeparator'], len = keys.length; i < len; i++) { key = keys[i] this.options[key] = options[key] || defaultOptions[key] } } Fuse.VERSION = '2.4.1' /** * Sets a new list for Fuse to match against. * @param {Array} list * @return {Array} The newly set list * @public */ Fuse.prototype.set = function (list) { this.list = list return list } Fuse.prototype.search = function (pattern) { if (this.options.verbose) log('\nSearch term:', pattern, '\n') this.pattern = pattern this.results = [] this.resultMap = {} this._keyMap = null this._prepareSearchers() this._startSearch() this._computeScore() this._sort() var output = this._format() return output } Fuse.prototype._prepareSearchers = function () { var options = this.options var pattern = this.pattern var searchFn = options.searchFn var tokens = pattern.split(options.tokenSeparator) var i = 0 var len = tokens.length if (this.options.tokenize) { this.tokenSearchers = [] for (; i < len; i++) { this.tokenSearchers.push(new searchFn(tokens[i], options)) } } this.fullSeacher = new searchFn(pattern, options) } Fuse.prototype._startSearch = function () { var options = this.options var getFn = options.getFn var list = this.list var listLen = list.length var keys = this.options.keys var keysLen = keys.length var key var weight var item = null var i var j // Check the first item in the list, if it's a string, then we assume // that every item in the list is also a string, and thus it's a flattened array. if (typeof list[0] === 'string') { // Iterate over every item for (i = 0; i < listLen; i++) { this._analyze('', list[i], i, i) } } else { this._keyMap = {} // Otherwise, the first item is an Object (hopefully), and thus the searching // is done on the values of the keys of each item. // Iterate over every item for (i = 0; i < listLen; i++) { item = list[i] // Iterate over every key for (j = 0; j < keysLen; j++) { key = keys[j] if (typeof key !== 'string') { weight = (1 - key.weight) || 1 this._keyMap[key.name] = { weight: weight } if (key.weight <= 0 || key.weight > 1) { throw new Error('Key weight has to be > 0 and <= 1') } key = key.name } else { this._keyMap[key] = { weight: 1 } } this._analyze(key, getFn(item, key, []), item, i) } } } } Fuse.prototype._analyze = function (key, text, entity, index) { var options = this.options var words var scores var exists = false var existingResult var averageScore var finalScore var scoresLen var mainSearchResult var tokenSearcher var termScores var word var tokenSearchResult var i var j // Check if the text can be searched if (text === undefined || text === null) { return } scores = [] if (typeof text === 'string') { words = text.split(options.tokenSeparator) if (options.verbose) log('---------\nKey:', key) if (this.options.tokenize) { for (i = 0; i < this.tokenSearchers.length; i++) { tokenSearcher = this.tokenSearchers[i] if (options.verbose) log('Pattern:', tokenSearcher.pattern) termScores = [] for (j = 0; j < words.length; j++) { word = words[j] tokenSearchResult = tokenSearcher.search(word) var obj = {} if (tokenSearchResult.isMatch) { obj[word] = tokenSearchResult.score exists = true scores.push(tokenSearchResult.score) } else { obj[word] = 1 scores.push(1) } termScores.push(obj) } if (options.verbose) log('Token scores:', termScores) } averageScore = scores[0] scoresLen = scores.length for (i = 1; i < scoresLen; i++) { averageScore += scores[i] } averageScore = averageScore / scoresLen if (options.verbose) log('Token score average:', averageScore) } mainSearchResult = this.fullSeacher.search(text) if (options.verbose) log('Full text score:', mainSearchResult.score) finalScore = mainSearchResult.score if (averageScore !== undefined) { finalScore = (finalScore + averageScore) / 2 } if (options.verbose) log('Score average:', finalScore) // If a match is found, add the item to <rawResults>, including its score if (exists || mainSearchResult.isMatch) { // Check if the item already exists in our results existingResult = this.resultMap[index] if (existingResult) { // Use the lowest score // existingResult.score, bitapResult.score existingResult.output.push({ key: key, score: finalScore, matchedIndices: mainSearchResult.matchedIndices }) } else { // Add it to the raw result list this.resultMap[index] = { item: entity, output: [{ key: key, score: finalScore, matchedIndices: mainSearchResult.matchedIndices }] } this.results.push(this.resultMap[index]) } } } else if (isArray(text)) { for (i = 0; i < text.length; i++) { this._analyze(key, text[i], entity, index) } } } Fuse.prototype._computeScore = function () { var i var j var keyMap = this._keyMap var totalScore var output var scoreLen var score var weight var results = this.results var bestScore var nScore if (this.options.verbose) log('\n\nComputing score:\n') for (i = 0; i < results.length; i++) { totalScore = 0 output = results[i].output scoreLen = output.length bestScore = 1 for (j = 0; j < scoreLen; j++) { score = output[j].score weight = keyMap ? keyMap[output[j].key].weight : 1 nScore = score * weight if (weight !== 1) { bestScore = Math.min(bestScore, nScore) } else { totalScore += nScore output[j].nScore = nScore } } if (bestScore === 1) { results[i].score = totalScore / scoreLen } else { results[i].score = bestScore } if (this.options.verbose) log(results[i]) } } Fuse.prototype._sort = function () { var options = this.options if (options.shouldSort) { if (options.verbose) log('\n\nSorting....') this.results.sort(options.sortFn) } } Fuse.prototype._format = function () { var options = this.options var getFn = options.getFn var finalOutput = [] var item var i var len var results = this.results var replaceValue var getItemAtIndex var include = options.include if (options.verbose) log('\n\nOutput:\n\n', results) // Helper function, here for speed-up, which replaces the item with its value, // if the options specifies it, replaceValue = options.id ? function (index) { results[index].item = getFn(results[index].item, options.id, [])[0] } : function () {} getItemAtIndex = function (index) { var record = results[index] var data var j var output var _item var _result // If `include` has values, put the item in the result if (include.length > 0) { data = { item: record.item } if (include.indexOf('matches') !== -1) { output = record.output data.matches = [] for (j = 0; j < output.length; j++) { _item = output[j] _result = { indices: _item.matchedIndices } if (_item.key) { _result.key = _item.key } data.matches.push(_result) } } if (include.indexOf('score') !== -1) { data.score = results[index].score } } else { data = record.item } return data } // From the results, push into a new array only the item identifier (if specified) // of the entire item. This is because we don't want to return the <results>, // since it contains other metadata for (i = 0, len = results.length; i < len; i++) { replaceValue(i) item = getItemAtIndex(i) finalOutput.push(item) } return finalOutput } // Helpers function deepValue (obj, path, list) { var firstSegment var remaining var dotIndex var value var i var len if (!path) { // If there's no path left, we've gotten to the object we care about. list.push(obj) } else { dotIndex = path.indexOf('.') if (dotIndex !== -1) { firstSegment = path.slice(0, dotIndex) remaining = path.slice(dotIndex + 1) } else { firstSegment = path } value = obj[firstSegment] if (value !== null && value !== undefined) { if (!remaining && (typeof value === 'string' || typeof value === 'number')) { list.push(value) } else if (isArray(value)) { // Search each item in the array. for (i = 0, len = value.length; i < len; i++) { deepValue(value[i], remaining, list) } } else if (remaining) { // An object. Recurse further. deepValue(value, remaining, list) } } } return list } function isArray (obj) { return Object.prototype.toString.call(obj) === '[object Array]' } /** * Adapted from "Diff, Match and Patch", by Google * * http://code.google.com/p/google-diff-match-patch/ * * Modified by: Kirollos Risk <kirollos@gmail.com> * ----------------------------------------------- * Details: the algorithm and structure was modified to allow the creation of * <Searcher> instances with a <search> method which does the actual * bitap search. The <pattern> (the string that is searched for) is only defined * once per instance and thus it eliminates redundant re-creation when searching * over a list of strings. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. */ function BitapSearcher (pattern, options) { options = options || {} this.options = options this.options.location = options.location || BitapSearcher.defaultOptions.location this.options.distance = 'distance' in options ? options.distance : BitapSearcher.defaultOptions.distance this.options.threshold = 'threshold' in options ? options.threshold : BitapSearcher.defaultOptions.threshold this.options.maxPatternLength = options.maxPatternLength || BitapSearcher.defaultOptions.maxPatternLength this.pattern = options.caseSensitive ? pattern : pattern.toLowerCase() this.patternLen = pattern.length if (this.patternLen <= this.options.maxPatternLength) { this.matchmask = 1 << (this.patternLen - 1) this.patternAlphabet = this._calculatePatternAlphabet() } } BitapSearcher.defaultOptions = { // Approximately where in the text is the pattern expected to be found? location: 0, // Determines how close the match must be to the fuzzy location (specified above). // An exact letter match which is 'distance' characters away from the fuzzy location // would score as a complete mismatch. A distance of '0' requires the match be at // the exact location specified, a threshold of '1000' would require a perfect match // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold. distance: 100, // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match // (of both letters and location), a threshold of '1.0' would match anything. threshold: 0.6, // Machine word size maxPatternLength: 32 } /** * Initialize the alphabet for the Bitap algorithm. * @return {Object} Hash of character locations. * @private */ BitapSearcher.prototype._calculatePatternAlphabet = function () { var mask = {}, i = 0 for (i = 0; i < this.patternLen; i++) { mask[this.pattern.charAt(i)] = 0 } for (i = 0; i < this.patternLen; i++) { mask[this.pattern.charAt(i)] |= 1 << (this.pattern.length - i - 1) } return mask } /** * Compute and return the score for a match with `e` errors and `x` location. * @param {number} errors Number of errors in match. * @param {number} location Location of match. * @return {number} Overall score for match (0.0 = good, 1.0 = bad). * @private */ BitapSearcher.prototype._bitapScore = function (errors, location) { var accuracy = errors / this.patternLen, proximity = Math.abs(this.options.location - location) if (!this.options.distance) { // Dodge divide by zero error. return proximity ? 1.0 : accuracy } return accuracy + (proximity / this.options.distance) } /** * Compute and return the result of the search * @param {String} text The text to search in * @return {Object} Literal containing: * {Boolean} isMatch Whether the text is a match or not * {Decimal} score Overall score for the match * @public */ BitapSearcher.prototype.search = function (text) { var options = this.options var i var j var textLen var location var threshold var bestLoc var binMin var binMid var binMax var start, finish var bitArr var lastBitArr var charMatch var score var locations var matches var isMatched var matchMask var matchedIndices var matchesLen var match text = options.caseSensitive ? text : text.toLowerCase() if (this.pattern === text) { // Exact match return { isMatch: true, score: 0, matchedIndices: [[0, text.length - 1]] } } // When pattern length is greater than the machine word length, just do a a regex comparison if (this.patternLen > options.maxPatternLength) { matches = text.match(new RegExp(this.pattern.replace(options.tokenSeparator, '|'))) isMatched = !!matches if (isMatched) { matchedIndices = [] for (i = 0, matchesLen = matches.length; i < matchesLen; i++) { match = matches[i] matchedIndices.push([text.indexOf(match), match.length - 1]) } } return { isMatch: isMatched, // TODO: revisit this score score: isMatched ? 0.5 : 1, matchedIndices: matchedIndices } } location = options.location // Set starting location at beginning text and initialize the alphabet. textLen = text.length // Highest score beyond which we give up. threshold = options.threshold // Is there a nearby exact match? (speedup) bestLoc = text.indexOf(this.pattern, location) // a mask of the matches matchMask = [] for (i = 0; i < textLen; i++) { matchMask[i] = 0 } if (bestLoc != -1) { threshold = Math.min(this._bitapScore(0, bestLoc), threshold) // What about in the other direction? (speed up) bestLoc = text.lastIndexOf(this.pattern, location + this.patternLen) if (bestLoc != -1) { threshold = Math.min(this._bitapScore(0, bestLoc), threshold) } } bestLoc = -1 score = 1 locations = [] binMax = this.patternLen + textLen for (i = 0; i < this.patternLen; i++) { // Scan for the best match; each iteration allows for one more error. // Run a binary search to determine how far from the match location we can stray // at this error level. binMin = 0 binMid = binMax while (binMin < binMid) { if (this._bitapScore(i, location + binMid) <= threshold) { binMin = binMid } else { binMax = binMid } binMid = Math.floor((binMax - binMin) / 2 + binMin) } // Use the result from this iteration as the maximum for the next. binMax = binMid start = Math.max(1, location - binMid + 1) finish = Math.min(location + binMid, textLen) + this.patternLen // Initialize the bit array bitArr = Array(finish + 2) bitArr[finish + 1] = (1 << i) - 1 for (j = finish; j >= start; j--) { charMatch = this.patternAlphabet[text.charAt(j - 1)] if (charMatch) { matchMask[j - 1] = 1 } if (i === 0) { // First pass: exact match. bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch } else { // Subsequent passes: fuzzy match. bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch | (((lastBitArr[j + 1] | lastBitArr[j]) << 1) | 1) | lastBitArr[j + 1] } if (bitArr[j] & this.matchmask) { score = this._bitapScore(i, j - 1) // This match will almost certainly be better than any existing match. // But check anyway. if (score <= threshold) { // Indeed it is threshold = score bestLoc = j - 1 locations.push(bestLoc) if (bestLoc > location) { // When passing loc, don't exceed our current distance from loc. start = Math.max(1, 2 * location - bestLoc) } else { // Already passed loc, downhill from here on in. break } } } } // No hope for a (better) match at greater error levels. if (this._bitapScore(i + 1, location) > threshold) { break } lastBitArr = bitArr } matchedIndices = this._getMatchedIndices(matchMask) // Count exact matches (those with a score of 0) to be "almost" exact return { isMatch: bestLoc >= 0, score: score === 0 ? 0.001 : score, matchedIndices: matchedIndices } } BitapSearcher.prototype._getMatchedIndices = function (matchMask) { var matchedIndices = [] var start = -1 var end = -1 var i = 0 var match var len = matchMask.length for (; i < len; i++) { match = matchMask[i] if (match && start === -1) { start = i } else if (!match && start !== -1) { end = i - 1 matchedIndices.push([start, end]) start = -1 } } if (matchMask[i - 1]) { matchedIndices.push([start, i - 1]) } return matchedIndices } // Export to Common JS Loader if (true) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = Fuse } else if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(function () { return Fuse }) } else { // Browser globals (root is window) global.Fuse = Fuse } })(this) /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _redux = __webpack_require__(4); var _index = __webpack_require__(18); var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Store = function () { function Store() { _classCallCheck(this, Store); this.store = (0, _redux.createStore)(_index2.default, window.devToolsExtension ? window.devToolsExtension() : undefined); } /** * Get store object (wrapping Redux method) * @return {Object} State */ _createClass(Store, [{ key: 'getState', value: function getState() { return this.store.getState(); } /** * Dispatch event to store (wrapped Redux method) * @param {Function} action Action function to trigger * @return */ }, { key: 'dispatch', value: function dispatch(action) { this.store.dispatch(action); } /** * Subscribe store to function call (wrapped Redux method) * @param {Function} onChange Function to trigger when state changes * @return */ }, { key: 'subscribe', value: function subscribe(onChange) { this.store.subscribe(onChange); } /** * Get items from store * @return {Array} Item objects */ }, { key: 'getItems', value: function getItems() { var state = this.store.getState(); return state.items; } /** * Get active items from store * @return {Array} Item objects */ }, { key: 'getItemsFilteredByActive', value: function getItemsFilteredByActive() { var items = this.getItems(); var values = items.filter(function (item) { return item.active === true; }, []); return values; } /** * Get items from store reduced to just their values * @return {Array} Item objects */ }, { key: 'getItemsReducedToValues', value: function getItemsReducedToValues() { var items = arguments.length <= 0 || arguments[0] === undefined ? this.getItems() : arguments[0]; var values = items.reduce(function (prev, current) { prev.push(current.value); return prev; }, []); return values; } /** * Get choices from store * @return {Array} Option objects */ }, { key: 'getChoices', value: function getChoices() { var state = this.store.getState(); return state.choices; } /** * Get active choices from store * @return {Array} Option objects */ }, { key: 'getChoicesFilteredByActive', value: function getChoicesFilteredByActive() { var choices = this.getChoices(); var values = choices.filter(function (choice) { return choice.active === true; }, []); return values; } /** * Get selectable choices from store * @return {Array} Option objects */ }, { key: 'getChoicesFilteredBySelectable', value: function getChoicesFilteredBySelectable() { var choices = this.getChoices(); var values = choices.filter(function (choice) { return choice.disabled !== true; }, []); return values; } /** * Get single choice by it's ID * @return {Object} Found choice */ }, { key: 'getChoiceById', value: function getChoiceById(id) { if (id) { var choices = this.getChoicesFilteredByActive(); var foundChoice = choices.find(function (choice) { return choice.id === parseInt(id, 10); }); return foundChoice; } return false; } /** * Get groups from store * @return {Array} Group objects */ }, { key: 'getGroups', value: function getGroups() { var state = this.store.getState(); return state.groups; } /** * Get active groups from store * @return {Array} Group objects */ }, { key: 'getGroupsFilteredByActive', value: function getGroupsFilteredByActive() { var groups = this.getGroups(); var choices = this.getChoices(); var values = groups.filter(function (group) { var isActive = group.active === true && group.disabled === false; var hasActiveOptions = choices.some(function (choice) { return choice.active === true && choice.disabled === false; }); return isActive && hasActiveOptions; }, []); return values; } }]); return Store; }(); exports.default = Store; module.exports = Store; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; var _createStore = __webpack_require__(5); var _createStore2 = _interopRequireDefault(_createStore); var _combineReducers = __webpack_require__(13); var _combineReducers2 = _interopRequireDefault(_combineReducers); var _bindActionCreators = __webpack_require__(15); var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); var _applyMiddleware = __webpack_require__(16); var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); var _compose = __webpack_require__(17); var _compose2 = _interopRequireDefault(_compose); var _warning = __webpack_require__(14); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (false) { (0, _warning2["default"])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } exports.createStore = _createStore2["default"]; exports.combineReducers = _combineReducers2["default"]; exports.bindActionCreators = _bindActionCreators2["default"]; exports.applyMiddleware = _applyMiddleware2["default"]; exports.compose = _compose2["default"]; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ActionTypes = undefined; exports["default"] = createStore; var _isPlainObject = __webpack_require__(6); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _symbolObservable = __webpack_require__(11); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = exports.ActionTypes = { INIT: '@@redux/INIT' }; /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [initialState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} enhancer The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, initialState, enhancer) { var _ref2; if (typeof initialState === 'function' && typeof enhancer === 'undefined') { enhancer = initialState; initialState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, initialState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = initialState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!(0, _isPlainObject2["default"])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[_symbolObservable2["default"]] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[_symbolObservable2["default"]] = observable, _ref2; } /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var getPrototype = __webpack_require__(7), isHostObject = __webpack_require__(9), isObjectLike = __webpack_require__(10); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, * else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return (typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); } module.exports = isPlainObject; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(8); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetPrototype = Object.getPrototypeOf; /** * Gets the `[[Prototype]]` of `value`. * * @private * @param {*} value The value to query. * @returns {null|Object} Returns the `[[Prototype]]`. */ var getPrototype = overArg(nativeGetPrototype, Object); module.exports = getPrototype; /***/ }, /* 8 */ /***/ function(module, exports) { /** * Creates a function that invokes `func` with its first argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 9 */ /***/ function(module, exports) { /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } module.exports = isHostObject; /***/ }, /* 10 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/* global window */ 'use strict'; module.exports = __webpack_require__(12)(global || window || this); /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 12 */ /***/ function(module, exports) { 'use strict'; module.exports = function symbolObservablePonyfill(root) { var result; var Symbol = root.Symbol; if (typeof Symbol === 'function') { if (Symbol.observable) { result = Symbol.observable; } else { result = Symbol('observable'); Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports["default"] = combineReducers; var _createStore = __webpack_require__(5); var _isPlainObject = __webpack_require__(6); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(14); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'initialState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2["default"])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key); }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerSanity(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); var sanityError; try { assertReducerSanity(finalReducers); } catch (e) { sanityError = e; } return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (sanityError) { throw sanityError; } if (false) { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action); if (warningMessage) { (0, _warning2["default"])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var i = 0; i < finalReducerKeys.length; i++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key]; var previousStateForKey = state[key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /***/ }, /* 14 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports["default"] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 15 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports["default"] = bindActionCreators; function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports["default"] = applyMiddleware; var _compose = __webpack_require__(17); var _compose2 = _interopRequireDefault(_compose); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, initialState, enhancer) { var store = createStore(reducer, initialState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2["default"].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }, /* 17 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = compose; /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } else { var _ret = function () { var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return { v: function v() { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); } }; }(); if (typeof _ret === "object") return _ret.v; } } /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _redux = __webpack_require__(4); var _items = __webpack_require__(19); var _items2 = _interopRequireDefault(_items); var _groups = __webpack_require__(20); var _groups2 = _interopRequireDefault(_groups); var _choices = __webpack_require__(21); var _choices2 = _interopRequireDefault(_choices); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var appReducer = (0, _redux.combineReducers)({ items: _items2.default, groups: _groups2.default, choices: _choices2.default }); var rootReducer = function rootReducer(passedState, action) { var state = passedState; // If we are clearing all items, groups and options we reassign // state and then pass that state to our proper reducer. This isn't // mutating our actual state // See: http://stackoverflow.com/a/35641992 if (action.type === 'CLEAR_ALL') { state = undefined; } return appReducer(state, action); }; exports.default = rootReducer; /***/ }, /* 19 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var items = function items() { var state = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; var action = arguments[1]; switch (action.type) { case 'ADD_ITEM': { // Add object to items array var newState = [].concat(_toConsumableArray(state), [{ id: action.id, choiceId: action.choiceId, value: action.value, label: action.label, active: true, highlighted: false }]); return newState.map(function (item) { if (item.highlighted) { item.highlighted = false; } return item; }); } case 'REMOVE_ITEM': { // Set item to inactive return state.map(function (item) { if (item.id === action.id) { item.active = false; } return item; }); } case 'HIGHLIGHT_ITEM': { return state.map(function (item) { if (item.id === action.id) { item.highlighted = action.highlighted; } return item; }); } default: { return state; } } }; exports.default = items; /***/ }, /* 20 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var groups = function groups() { var state = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; var action = arguments[1]; switch (action.type) { case 'ADD_GROUP': { return [].concat(_toConsumableArray(state), [{ id: action.id, value: action.value, active: action.active, disabled: action.disabled }]); } default: { return state; } } }; exports.default = groups; /***/ }, /* 21 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; 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 choices = function choices() { var state = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; var action = arguments[1]; switch (action.type) { case 'ADD_CHOICE': { /* A disabled choice appears in the choice dropdown but cannot be selected A selected choice has been added to the passed input's value (added as an item) An active choice appears within the choice dropdown */ return [].concat(_toConsumableArray(state), [{ id: action.id, groupId: action.groupId, value: action.value, label: action.label, disabled: action.disabled, selected: false, active: true, score: 9999 }]); } case 'ADD_ITEM': { var newState = state; // If all choices need to be activated if (action.activateOptions) { newState = state.map(function (choice) { choice.active = action.active; return choice; }); } // When an item is added and it has an associated choice, // we want to disable it so it can't be chosen again if (action.choiceId > -1) { newState = state.map(function (choice) { if (choice.id === parseInt(action.choiceId, 10)) { choice.selected = true; } return choice; }); } return newState; } case 'REMOVE_ITEM': { // When an item is removed and it has an associated choice, // we want to re-enable it so it can be chosen again if (action.choiceId > -1) { return state.map(function (choice) { if (choice.id === parseInt(action.choiceId, 10)) { choice.selected = false; } return choice; }); } return state; } case 'FILTER_CHOICES': { var _ret = function () { var filteredResults = action.results; var filteredState = state.map(function (choice) { // Set active state based on whether choice is // within filtered results choice.active = filteredResults.some(function (result) { if (result.item.id === choice.id) { choice.score = result.score; return true; } return false; }); return choice; }); return { v: filteredState }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } case 'ACTIVATE_CHOICES': { return state.map(function (choice) { choice.active = action.active; return choice; }); } default: { return state; } } }; exports.default = choices; /***/ }, /* 22 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var addItem = exports.addItem = function addItem(value, label, id, choiceId, activateOptions) { return { type: 'ADD_ITEM', value: value, label: label, id: id, choiceId: choiceId, activateOptions: activateOptions }; }; var removeItem = exports.removeItem = function removeItem(id, choiceId) { return { type: 'REMOVE_ITEM', id: id, choiceId: choiceId }; }; var highlightItem = exports.highlightItem = function highlightItem(id, highlighted) { return { type: 'HIGHLIGHT_ITEM', id: id, highlighted: highlighted }; }; var addChoice = exports.addChoice = function addChoice(value, label, id, groupId, disabled) { return { type: 'ADD_CHOICE', value: value, label: label, id: id, groupId: groupId, disabled: disabled }; }; var filterChoices = exports.filterChoices = function filterChoices(results) { return { type: 'FILTER_CHOICES', results: results }; }; var activateChoices = exports.activateChoices = function activateChoices() { var active = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; return { type: 'ACTIVATE_CHOICES', active: active }; }; var addGroup = exports.addGroup = function addGroup(value, id, active, disabled) { return { type: 'ADD_GROUP', value: value, id: id, active: active, disabled: disabled }; }; var clearAll = exports.clearAll = function clearAll() { return { type: 'CLEAR_ALL' }; }; /***/ }, /* 23 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /* eslint-disable */ /** * Capitalises the first letter of each word in a string * @param {String} str String to capitalise * @return {String} Capitalised string */ var capitalise = exports.capitalise = function capitalise(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); }; /** * Tests the type of an object * @param {String} type Type to test object against * @param {Object} obj Object to be tested * @return {Boolean} */ var isType = exports.isType = function isType(type, obj) { var clas = Object.prototype.toString.call(obj).slice(8, -1); return obj !== undefined && obj !== null && clas === type; }; /** * Tests to see if a passed object is a node * @param {Object} obj Object to be tested * @return {Boolean} */ var isNode = exports.isNode = function isNode(o) { return (typeof Node === "undefined" ? "undefined" : _typeof(Node)) === "object" ? o instanceof Node : o && (typeof o === "undefined" ? "undefined" : _typeof(o)) === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string"; }; /** * Tests to see if a passed object is an element * @param {Object} obj Object to be tested * @return {Boolean} */ var isElement = exports.isElement = function isElement(o) { return (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) === "object" ? o instanceof HTMLElement : //DOM2 o && (typeof o === "undefined" ? "undefined" : _typeof(o)) === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"; }; /** * Merges unspecified amount of objects into new object * @private * @return {Object} Merged object of arguments */ var extend = exports.extend = function extend() { var extended = {}; var deep = false; var length = arguments.length; /** * Merge one object into another * @param {Object} obj Object to merge into extended object */ var merge = function merge(obj) { for (var prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { // If deep merge and property is an object, merge properties if (deep && isType('Object', obj[prop])) { extended[prop] = extend(true, extended[prop], obj[prop]); } else { extended[prop] = obj[prop]; } } } }; // Loop through each passed argument for (var i = 0; i < length; i++) { // store argument at position i var obj = arguments[i]; // If we are in fact dealing with an object, merge it. Otherwise throw error if (isType('Object', obj)) { merge(obj); } else { console.error('Custom options must be an object'); } } return extended; }; /** * CSS transition end event listener * @return */ var whichTransitionEvent = exports.whichTransitionEvent = function whichTransitionEvent() { var t, el = document.createElement("fakeelement"); var transitions = { "transition": "transitionend", "OTransition": "oTransitionEnd", "MozTransition": "transitionend", "WebkitTransition": "webkitTransitionEnd" }; for (t in transitions) { if (el.style[t] !== undefined) { return transitions[t]; } } }; /** * CSS animation end event listener * @return */ var whichAnimationEvent = exports.whichAnimationEvent = function whichAnimationEvent() { var t, el = document.createElement('fakeelement'); var animations = { 'animation': 'animationend', 'OAnimation': 'oAnimationEnd', 'MozAnimation': 'animationend', 'WebkitAnimation': 'webkitAnimationEnd' }; for (t in animations) { if (el.style[t] !== undefined) { return animations[t]; } } }; /** * Get the ancestors of each element in the current set of matched elements, * up to but not including the element matched by the selector * @param {NodeElement} elem Element to begin search from * @param {NodeElement} parent Parent to find * @param {String} selector Class to find * @return {Array} Array of parent elements */ var getParentsUntil = exports.getParentsUntil = function getParentsUntil(elem, parent, selector) { var parents = []; // Get matches for (; elem && elem !== document; elem = elem.parentNode) { // Check if parent has been reached if (parent) { var parentType = parent.charAt(0); // If parent is a class if (parentType === '.') { if (elem.classList.contains(parent.substr(1))) { break; } } // If parent is an ID if (parentType === '#') { if (elem.id === parent.substr(1)) { break; } } // If parent is a data attribute if (parentType === '[') { if (elem.hasAttribute(parent.substr(1, parent.length - 1))) { break; } } // If parent is a tag if (elem.tagName.toLowerCase() === parent) { break; } } if (selector) { var selectorType = selector.charAt(0); // If selector is a class if (selectorType === '.') { if (elem.classList.contains(selector.substr(1))) { parents.push(elem); } } // If selector is an ID if (selectorType === '#') { if (elem.id === selector.substr(1)) { parents.push(elem); } } // If selector is a data attribute if (selectorType === '[') { if (elem.hasAttribute(selector.substr(1, selector.length - 1))) { parents.push(elem); } } // If selector is a tag if (elem.tagName.toLowerCase() === selector) { parents.push(elem); } } else { parents.push(elem); } } // Return parents if any exist if (parents.length === 0) { return null; } else { return parents; } }; var wrap = exports.wrap = function wrap(element, wrapper) { wrapper = wrapper || document.createElement('div'); if (element.nextSibling) { element.parentNode.insertBefore(wrapper, element.nextSibling); } else { element.parentNode.appendChild(wrapper); } return wrapper.appendChild(element); }; var getSiblings = exports.getSiblings = function getSiblings(elem) { var siblings = []; var sibling = elem.parentNode.firstChild; for (; sibling; sibling = sibling.nextSibling) { if (sibling.nodeType === 1 && sibling !== elem) { siblings.push(sibling); } } return siblings; }; /** * Find ancestor in DOM tree * @param {NodeElement} el Element to start search from * @param {[type]} cls Class of parent * @return {NodeElement} Found parent element */ var findAncestor = exports.findAncestor = function findAncestor(el, cls) { while ((el = el.parentElement) && !el.classList.contains(cls)) {} return el; }; /** * Debounce an event handler. * @param {Function} func Function to run after wait * @param {Number} wait The delay before the function is executed * @param {Boolean} immediate If passed, trigger the function on the leading edge, instead of the trailing. * @return {Function} A function will be called after it stops being called for a given delay */ var debounce = exports.debounce = function debounce(func, wait, immediate) { var timeout; return function () { var context = this, args = arguments; var later = function later() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; /** * Get an element's distance from the top of the page * @private * @param {NodeElement} el Element to test for * @return {Number} Elements Distance from top of page */ var getElemDistance = exports.getElemDistance = function getElemDistance(el) { var location = 0; if (el.offsetParent) { do { location += el.offsetTop; el = el.offsetParent; } while (el); } return location >= 0 ? location : 0; }; /** * Determine element height multiplied by any offsets * @private * @param {HTMLElement} el Element to test for * @return {Number} Height of element */ var getElementOffset = exports.getElementOffset = function getElementOffset(el, offset) { var elOffset = offset; if (elOffset > 1) elOffset = 1; if (elOffset > 0) elOffset = 0; return Math.max(el.offsetHeight * elOffset); }; /** * Get the next or previous element from a given start point * @param {HTMLElement} startEl Element to start position from * @param {String} className The class we will look through * @param {Number} direction Positive next element, negative previous element * @return {[HTMLElement} Found element */ var getAdjacentEl = exports.getAdjacentEl = function getAdjacentEl(startEl, className) { var direction = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2]; if (!startEl || !className) return; var parent = startEl.parentNode.parentNode; var children = Array.from(parent.querySelectorAll(className)); var startPos = children.indexOf(startEl); var operatorDirection = direction > 0 ? 1 : -1; return children[startPos + operatorDirection]; }; /** * Get scroll position based on top/bottom position * @private * @return {String} Position of scroll */ var getScrollPosition = exports.getScrollPosition = function getScrollPosition(position) { if (position === 'bottom') { // Scroll position from the bottom of the viewport return Math.max((window.scrollY || window.pageYOffset) + (window.innerHeight || document.documentElement.clientHeight)); } else { // Scroll position from the top of the viewport return window.scrollY || window.pageYOffset; } }; /** * Determine whether an element is within the viewport * @param {HTMLElement} el Element to test * @return {String} Position of scroll * @return {Boolean} */ var isInView = exports.isInView = function isInView(el, position, offset) { // If the user has scrolled further than the distance from the element to the top of its parent return this.getScrollPosition(position) > this.getElemDistance(el) + this.getElementOffset(el, offset) ? true : false; }; /** * Determine whether an element is within * @param {HTMLElement} el Element to test * @param {HTMLElement} parent Scrolling parent * @param {Number} direction Whether element is visible from above or below * @return {Boolean} */ var isScrolledIntoView = exports.isScrolledIntoView = function isScrolledIntoView(el, parent) { var direction = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2]; if (!el) return; var isVisible = void 0; if (direction > 0) { // In view from bottom isVisible = parent.scrollTop + parent.offsetHeight >= el.offsetTop + el.offsetHeight; } else { // In view from top isVisible = el.offsetTop >= parent.scrollTop; } return isVisible; }; /** * Remove html tags from a string * @param {String} Initial string/html * @return {String} Sanitised string */ var stripHTML = exports.stripHTML = function stripHTML(html) { var el = document.createElement("DIV"); el.innerHTML = html; return el.textContent || el.innerText || ""; }; /** * Adds animation to an element and removes it upon animation completion * @param {Element} el Element to add animation to * @param {String} animation Animation class to add to element * @return */ var addAnimation = exports.addAnimation = function addAnimation(el, animation) { var animationEvent = whichAnimationEvent(); var removeAnimation = function removeAnimation() { el.classList.remove(animation); el.removeEventListener(animationEvent, removeAnimation, false); }; el.classList.add(animation); el.addEventListener(animationEvent, removeAnimation, false); }; /** * Get a random number between a range * @param {Number} min Minimum range * @param {Number} max Maximum range * @return {Number} Random number */ var getRandomNumber = exports.getRandomNumber = function getRandomNumber(min, max) { return Math.floor(Math.random() * (max - min) + min); }; /** * Turn a string into a node * @param {String} String to convert * @return {HTMLElement} Converted node element */ var strToEl = exports.strToEl = function () { var tmpEl = document.createElement('div'); return function (str) { var r; tmpEl.innerHTML = str; r = tmpEl.children[0]; while (tmpEl.firstChild) { tmpEl.removeChild(tmpEl.firstChild); } return r; }; }(); /** * Sets the width of a passed input based on its value * @return {Number} Width of input */ var getWidthOfInput = exports.getWidthOfInput = function getWidthOfInput(input) { var value = input.value || input.placeholder; var width = input.offsetWidth; if (value) { var testEl = strToEl("<span>" + value + "</span>"); testEl.style.position = 'absolute'; testEl.style.padding = '0'; testEl.style.top = '-9999px'; testEl.style.left = '-9999px'; testEl.style.width = 'auto'; testEl.style.whiteSpace = 'pre'; document.body.appendChild(testEl); if (value && testEl.offsetWidth !== input.offsetWidth) { width = testEl.offsetWidth + 4; } document.body.removeChild(testEl); } return width + "px"; }; var sortByAlpha = exports.sortByAlpha = function sortByAlpha(a, b) { var labelA = (a.label || a.value).toLowerCase(); var labelB = (b.label || b.value).toLowerCase(); if (labelA < labelB) return -1; if (labelA > labelB) return 1; return 0; }; var sortByScore = exports.sortByScore = function sortByScore(a, b) { return a.score - b.score; }; /***/ }, /* 24 */ /***/ function(module, exports) { 'use strict'; /* eslint-disable */ // Production steps of ECMA-262, Edition 6, 22.1.2.1 // Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from if (!Array.from) { Array.from = function () { var toStr = Object.prototype.toString; var isCallable = function isCallable(fn) { return typeof fn === 'function' || toStr.call(fn) === '[object Function]'; }; var toInteger = function toInteger(value) { var number = Number(value); if (isNaN(number)) { return 0; } if (number === 0 || !isFinite(number)) { return number; } return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); }; var maxSafeInteger = Math.pow(2, 53) - 1; var toLength = function toLength(value) { var len = toInteger(value); return Math.min(Math.max(len, 0), maxSafeInteger); }; // The length property of the from method is 1. return function from(arrayLike /*, mapFn, thisArg */) { // 1. Let C be the this value. var C = this; // 2. Let items be ToObject(arrayLike). var items = Object(arrayLike); // 3. ReturnIfAbrupt(items). if (arrayLike == null) { throw new TypeError("Array.from requires an array-like object - not null or undefined"); } // 4. If mapfn is undefined, then let mapping be false. var mapFn = arguments.length > 1 ? arguments[1] : void undefined; var T; if (typeof mapFn !== 'undefined') { // 5. else // 5. a If IsCallable(mapfn) is false, throw a TypeError exception. if (!isCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 2) { T = arguments[2]; } } // 10. Let lenValue be Get(items, "length"). // 11. Let len be ToLength(lenValue). var len = toLength(items.length); // 13. If IsConstructor(C) is true, then // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len. // 14. a. Else, Let A be ArrayCreate(len). var A = isCallable(C) ? Object(new C(len)) : new Array(len); // 16. Let k be 0. var k = 0; // 17. Repeat, while k < len… (also steps a - h) var kValue; while (k < len) { kValue = items[k]; if (mapFn) { A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k); } else { A[k] = kValue; } k += 1; } // 18. Let putStatus be Put(A, "length", len, true). A.length = len; // 20. Return A. return A; }; }(); } // Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find if (!Array.prototype.find) { Array.prototype.find = function (predicate) { 'use strict'; if (this == null) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; }; } /***/ } /******/ ]); //# sourceMappingURL=choices.js.map
ajax/libs/yui/3.18.0/event-focus/event-focus-debug.js
vfonic/cdnjs
YUI.add('event-focus', function (Y, NAME) { /** * Adds bubbling and delegation support to DOM events focus and blur. * * @module event * @submodule event-focus */ var Event = Y.Event, YLang = Y.Lang, isString = YLang.isString, arrayIndex = Y.Array.indexOf, useActivate = (function() { // Changing the structure of this test, so that it doesn't use inline JS in HTML, // which throws an exception in Win8 packaged apps, due to additional security restrictions: // http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences var supported = false, doc = Y.config.doc, p; if (doc) { p = doc.createElement("p"); p.setAttribute("onbeforeactivate", ";"); // onbeforeactivate is a function in IE8+. // onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below). // onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test). // onbeforeactivate is undefined in Webkit/Gecko. // onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick). supported = (p.onbeforeactivate !== undefined); } return supported; }()); function define(type, proxy, directEvent) { var nodeDataKey = '_' + type + 'Notifiers'; Y.Event.define(type, { _useActivate : useActivate, _attach: function (el, notifier, delegate) { if (Y.DOM.isWindow(el)) { return Event._attach([type, function (e) { notifier.fire(e); }, el]); } else { return Event._attach( [proxy, this._proxy, el, this, notifier, delegate], { capture: true }); } }, _proxy: function (e, notifier, delegate) { var target = e.target, currentTarget = e.currentTarget, notifiers = target.getData(nodeDataKey), yuid = Y.stamp(currentTarget._node), defer = (useActivate || target !== currentTarget), directSub; notifier.currentTarget = (delegate) ? target : currentTarget; notifier.container = (delegate) ? currentTarget : null; // Maintain a list to handle subscriptions from nested // containers div#a>div#b>input #a.on(focus..) #b.on(focus..), // use one focus or blur subscription that fires notifiers from // #b then #a to emulate bubble sequence. if (!notifiers) { notifiers = {}; target.setData(nodeDataKey, notifiers); // only subscribe to the element's focus if the target is // not the current target ( if (defer) { directSub = Event._attach( [directEvent, this._notify, target._node]).sub; directSub.once = true; } } else { // In old IE, defer is always true. In capture-phase browsers, // The delegate subscriptions will be encountered first, which // will establish the notifiers data and direct subscription // on the node. If there is also a direct subscription to the // node's focus/blur, it should not call _notify because the // direct subscription from the delegate sub(s) exists, which // will call _notify. So this avoids _notify being called // twice, unnecessarily. defer = true; } if (!notifiers[yuid]) { notifiers[yuid] = []; } notifiers[yuid].push(notifier); if (!defer) { this._notify(e); } }, _notify: function (e, container) { var currentTarget = e.currentTarget, notifierData = currentTarget.getData(nodeDataKey), axisNodes = currentTarget.ancestors(), doc = currentTarget.get('ownerDocument'), delegates = [], // Used to escape loops when there are no more // notifiers to consider count = notifierData ? Y.Object.keys(notifierData).length : 0, target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret; // clear the notifications list (mainly for delegation) currentTarget.clearData(nodeDataKey); // Order the delegate subs by their placement in the parent axis axisNodes.push(currentTarget); // document.get('ownerDocument') returns null // which we'll use to prevent having duplicate Nodes in the list if (doc) { axisNodes.unshift(doc); } // ancestors() returns the Nodes from top to bottom axisNodes._nodes.reverse(); if (count) { // Store the count for step 2 tmp = count; axisNodes.some(function (node) { var yuid = Y.stamp(node), notifiers = notifierData[yuid], i, len; if (notifiers) { count--; for (i = 0, len = notifiers.length; i < len; ++i) { if (notifiers[i].handle.sub.filter) { delegates.push(notifiers[i]); } } } return !count; }); count = tmp; } // Walk up the parent axis, notifying direct subscriptions and // testing delegate filters. while (count && (target = axisNodes.shift())) { yuid = Y.stamp(target); notifiers = notifierData[yuid]; if (notifiers) { for (i = 0, len = notifiers.length; i < len; ++i) { notifier = notifiers[i]; sub = notifier.handle.sub; match = true; e.currentTarget = target; if (sub.filter) { match = sub.filter.apply(target, [target, e].concat(sub.args || [])); // No longer necessary to test against this // delegate subscription for the nodes along // the parent axis. delegates.splice( arrayIndex(delegates, notifier), 1); } if (match) { // undefined for direct subs e.container = notifier.container; ret = notifier.fire(e); } if (ret === false || e.stopped === 2) { break; } } delete notifiers[yuid]; count--; } if (e.stopped !== 2) { // delegates come after subs targeting this specific node // because they would not normally report until they'd // bubbled to the container node. for (i = 0, len = delegates.length; i < len; ++i) { notifier = delegates[i]; sub = notifier.handle.sub; if (sub.filter.apply(target, [target, e].concat(sub.args || []))) { e.container = notifier.container; e.currentTarget = target; ret = notifier.fire(e); } if (ret === false || e.stopped === 2 || // If e.stopPropagation() is called, notify any // delegate subs from the same container, but break // once the container changes. This emulates // delegate() behavior for events like 'click' which // won't notify delegates higher up the parent axis. (e.stopped && delegates[i+1] && delegates[i+1].container !== notifier.container)) { break; } } } if (e.stopped) { break; } } }, on: function (node, sub, notifier) { sub.handle = this._attach(node._node, notifier); }, detach: function (node, sub) { sub.handle.detach(); }, delegate: function (node, sub, notifier, filter) { if (isString(filter)) { sub.filter = function (target) { return Y.Selector.test(target._node, filter, node === target ? null : node._node); }; } sub.handle = this._attach(node._node, notifier, true); }, detachDelegate: function (node, sub) { sub.handle.detach(); } }, true); } // For IE, we need to defer to focusin rather than focus because // `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate, // el.onfocusin, doSomething, then el.onfocus. All others support capture // phase focus, which executes before doSomething. To guarantee consistent // behavior for this use case, IE's direct subscriptions are made against // focusin so subscribers will be notified before js following el.focus() is // executed. if (useActivate) { // name capture phase direct subscription define("focus", "beforeactivate", "focusin"); define("blur", "beforedeactivate", "focusout"); } else { define("focus", "focus", "focus"); define("blur", "blur", "blur"); } }, '3.18.0', {"requires": ["event-synthetic"]});
app/javascript/mastodon/features/compose/containers/sensitive_button_container.js
pfm-eyesightjp/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import IconButton from '../../../components/icon_button'; import { changeComposeSensitivity } from '../../../actions/compose'; import Motion from 'react-motion/lib/Motion'; import spring from 'react-motion/lib/spring'; import { injectIntl, defineMessages } from 'react-intl'; const messages = defineMessages({ title: { id: 'compose_form.sensitive', defaultMessage: 'Mark media as sensitive' }, }); const mapStateToProps = state => ({ visible: state.getIn(['compose', 'media_attachments']).size > 0, active: state.getIn(['compose', 'sensitive']), disabled: state.getIn(['compose', 'spoiler']), }); const mapDispatchToProps = dispatch => ({ onClick () { dispatch(changeComposeSensitivity()); }, }); class SensitiveButton extends React.PureComponent { static propTypes = { visible: PropTypes.bool, active: PropTypes.bool, disabled: PropTypes.bool, onClick: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { visible, active, disabled, onClick, intl } = this.props; return ( <Motion defaultStyle={{ scale: 0.87 }} style={{ scale: spring(visible ? 1 : 0.87, { stiffness: 200, damping: 3 }) }}> {({ scale }) => { const icon = active ? 'eye-slash' : 'eye'; const className = classNames('compose-form__sensitive-button', { 'compose-form__sensitive-button--visible': visible, }); return ( <div className={className} style={{ transform: `translateZ(0) scale(${scale})` }}> <IconButton className='compose-form__sensitive-button__icon' title={intl.formatMessage(messages.title)} icon={icon} onClick={onClick} size={18} active={active} disabled={disabled} style={{ lineHeight: null, height: null }} inverted /> </div> ); }} </Motion> ); } } export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(SensitiveButton));
packages/react/src/components/InlineLoading/InlineLoading.js
carbon-design-system/carbon-components
/** * 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 PropTypes from 'prop-types'; import classNames from 'classnames'; import { CheckmarkFilled16, ErrorFilled16 } from '@carbon/icons-react'; import deprecate from '../../prop-types/deprecate'; import Loading from '../Loading'; import { usePrefix } from '../../internal/usePrefix'; export default function InlineLoading({ className, success, status = success ? 'finished' : 'active', iconDescription, description, onSuccess, successDelay, ...other }) { const prefix = usePrefix(); const loadingClasses = classNames(`${prefix}--inline-loading`, className); const getLoading = () => { if (status === 'error') { return ( <ErrorFilled16 className={`${prefix}--inline-loading--error`}> <title>{iconDescription}</title> </ErrorFilled16> ); } if (status === 'finished') { setTimeout(() => { if (onSuccess) { onSuccess(); } }, successDelay); return ( <CheckmarkFilled16 className={`${prefix}--inline-loading__checkmark-container`}> <title>{iconDescription}</title> </CheckmarkFilled16> ); } if (status === 'inactive' || status === 'active') { return ( <Loading small description={iconDescription} withOverlay={false} active={status === 'active'} /> ); } return undefined; }; const loadingText = ( <div className={`${prefix}--inline-loading__text`}>{description}</div> ); const loading = getLoading(); const loadingAnimation = loading && ( <div className={`${prefix}--inline-loading__animation`}>{loading}</div> ); return ( <div className={loadingClasses} {...other} aria-live={'assertive' || other['aria-live']}> {loadingAnimation} {description && loadingText} </div> ); } InlineLoading.propTypes = { /** * Specify a custom className to be applied to the container node */ className: PropTypes.string, /** * Specify the description for the inline loading text */ description: PropTypes.node, /** * Specify the description for the inline loading text */ iconDescription: PropTypes.string, /** * Provide an optional handler to be invoked when <InlineLoading> is * successful */ onSuccess: PropTypes.func, /** * Specify the loading status */ status: PropTypes.oneOf(['inactive', 'active', 'finished', 'error']), /** * Specify whether the load was successful */ success: deprecate( PropTypes.bool, `\nThe prop \`success\` for InlineLoading has been deprecated in favor of \`status\`. Please use \`status="finished"\` instead.` ), /** * Provide a delay for the `setTimeout` for success */ successDelay: PropTypes.number, }; InlineLoading.defaultProps = { successDelay: 1500, };
docs/app/Examples/modules/Search/Variations/SearchExampleAligned.js
aabustamante/Semantic-UI-React
import React from 'react' import SearchExampleStandard from '../Types/SearchExampleStandard' const SearchExampleAligned = () => <SearchExampleStandard aligned='right' /> export default SearchExampleAligned
js/container/ArticleDetail.js
yourwafer/u148
import React from 'react'; import ReactNative from 'react-native'; import { connect } from 'react-redux'; import moment from 'moment'; import ArticleService from '../service/ArticleService'; import template from '../resources/html_tpl'; const { WebView, StyleSheet, Platform, View } = ReactNative; class ArticleDetail extends React.Component { constructor(props) { super(props); this.state = { content: this.buildContentWithHtml('') }; ArticleService.loadArticleDetail(props.article.id).then(content => { this.setState({ content: this.buildContentWithHtml(content) }); }); } componentDidUpdate(prevProps, prevState){ if(Platform.OS.toLocaleLowerCase() === 'android'){ requestAnimationFrame(() => { this.webView.reload(); }); } } buildContentWithHtml = (content) => { let article = this.props.article; const createTime = moment(article.create_time * 1000).format('YYYY-MM-DD'); return template.replace('{CONTENT}', content) .replace('{U_AUTHOR}', `${article.usr.nickname} ${createTime}`) .replace('{U_COMMENT}', 1) .replace('{TITLE}', article.title); } render() { return ( <WebView ref = {(e) => {this.webView = e;}} style={styles.webView} source={{html: this.state.content}} scalesPageToFit={true} /> ); } } const styles = StyleSheet.create({ webView: { flex: 1 } }); const mapState = (state) => { return { article: state.article }; }; export default connect(mapState)(ArticleDetail);
ajax/libs/core-js/0.4.2/library.js
RoryStolzenberg/cdnjs
/** * Core.js 0.4.2 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2015 Denis Pushkarev */ !function(returnThis, framework, undefined){ 'use strict'; /****************************************************************************** * Module : common * ******************************************************************************/ var global = returnThis() // Shortcuts for [[Class]] & property names , OBJECT = 'Object' , FUNCTION = 'Function' , ARRAY = 'Array' , STRING = 'String' , NUMBER = 'Number' , REGEXP = 'RegExp' , DATE = 'Date' , MAP = 'Map' , SET = 'Set' , WEAKMAP = 'WeakMap' , WEAKSET = 'WeakSet' , SYMBOL = 'Symbol' , PROMISE = 'Promise' , MATH = 'Math' , ARGUMENTS = 'Arguments' , PROTOTYPE = 'prototype' , CONSTRUCTOR = 'constructor' , TO_STRING = 'toString' , TO_STRING_TAG = TO_STRING + 'Tag' , TO_LOCALE = 'toLocaleString' , HAS_OWN = 'hasOwnProperty' , FOR_EACH = 'forEach' , ITERATOR = 'iterator' , FF_ITERATOR = '@@' + ITERATOR , PROCESS = 'process' , CREATE_ELEMENT = 'createElement' // Aliases global objects and prototypes , Function = global[FUNCTION] , Object = global[OBJECT] , Array = global[ARRAY] , String = global[STRING] , Number = global[NUMBER] , RegExp = global[REGEXP] , Date = global[DATE] , Map = global[MAP] , Set = global[SET] , WeakMap = global[WEAKMAP] , WeakSet = global[WEAKSET] , Symbol = global[SYMBOL] , Math = global[MATH] , TypeError = global.TypeError , setTimeout = global.setTimeout , setImmediate = global.setImmediate , clearImmediate = global.clearImmediate , process = global[PROCESS] , nextTick = process && process.nextTick , document = global.document , html = document && document.documentElement , navigator = global.navigator , define = global.define , ArrayProto = Array[PROTOTYPE] , ObjectProto = Object[PROTOTYPE] , FunctionProto = Function[PROTOTYPE] , Infinity = 1 / 0 , DOT = '.'; // http://jsperf.com/core-js-isobject function isObject(it){ return it != null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } // Native function? var isNative = ctx(/./.test, /\[native code\]\s*\}\s*$/, 1); // Object internal [[Class]] or toStringTag // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring var buildIn = { Undefined: 1, Null: 1, Array: 1, String: 1, Arguments: 1, Function: 1, Error: 1, Boolean: 1, Number: 1, Date: 1, RegExp:1 } , toString = ObjectProto[TO_STRING]; function setToStringTag(it, tag, stat){ if(it && !has(it = stat ? it : it[PROTOTYPE], SYMBOL_TAG))hidden(it, SYMBOL_TAG, tag); } function cof(it){ return it == undefined ? it === undefined ? 'Undefined' : 'Null' : toString.call(it).slice(8, -1); } function classof(it){ var klass = cof(it), tag; return klass == OBJECT && (tag = it[SYMBOL_TAG]) ? has(buildIn, tag) ? '~' + tag : tag : klass; } // Function var call = FunctionProto.call , apply = FunctionProto.apply , REFERENCE_GET; // Partial apply function part(/* ...args */){ var length = arguments.length , args = Array(length) , i = 0 , _ = path._ , holder = false; while(length > i)if((args[i] = arguments[i++]) === _)holder = true; return partial(this, args, length, holder, _, false); } // Internal partial application & context binding function partial(fn, argsPart, lengthPart, holder, _, bind, context){ assertFunction(fn); return function(/* ...args */){ var that = bind ? context : this , length = arguments.length , i = 0, j = 0, args; if(!holder && !length)return invoke(fn, argsPart, that); args = argsPart.slice(); if(holder)for(;lengthPart > i; i++)if(args[i] === _)args[i] = arguments[j++]; while(length > j)args.push(arguments[j++]); return invoke(fn, args, that); } } // Optional / simple context binding function ctx(fn, that, length){ assertFunction(fn); if(~length && that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); } case 2: return function(a, b){ return fn.call(that, a, b); } case 3: return function(a, b, c){ return fn.call(that, a, b, c); } } return function(/* ...args */){ return fn.apply(that, arguments); } } // Fast apply // http://jsperf.lnkit.com/fast-apply/5 function invoke(fn, args, that){ var un = that === undefined; switch(args.length | 0){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); } function construct(target, argumentsList){ var instance = create(target[PROTOTYPE]) , result = apply.call(target, instance, argumentsList); return isObject(result) ? result : instance; } // Object: var create = Object.create , getPrototypeOf = Object.getPrototypeOf , setPrototypeOf = Object.setPrototypeOf , defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , getOwnDescriptor = Object.getOwnPropertyDescriptor , getKeys = Object.keys , getNames = Object.getOwnPropertyNames , getSymbols = Object.getOwnPropertySymbols , has = ctx(call, ObjectProto[HAS_OWN], 2) // Dummy, fix for not array-like ES3 string in es5 module , ES5Object = Object; function returnIt(it){ return it; } function get(object, key){ if(has(object, key))return object[key]; } function ownKeys(it){ return getSymbols ? getNames(it).concat(getSymbols(it)) : getNames(it); } // 19.1.2.1 Object.assign(target, source, ...) var assign = Object.assign || function(target, source){ var T = Object(assertDefined(target)) , l = arguments.length , i = 1; while(l > i){ var S = ES5Object(arguments[i++]) , keys = getKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; } function keyOf(object, el){ var O = ES5Object(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; } // Array // array('str1,str2,str3') => ['str1', 'str2', 'str3'] function array(it){ return String(it).split(','); } var push = ArrayProto.push , unshift = ArrayProto.unshift , slice = ArrayProto.slice , splice = ArrayProto.splice , indexOf = ArrayProto.indexOf , forEach = ArrayProto[FOR_EACH]; /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findIndex */ function createArrayMethod(type){ var isMap = type == 1 , isFilter = type == 2 , isSome = type == 3 , isEvery = type == 4 , isFindIndex = type == 6 , noholes = type == 5 || isFindIndex; return function(callbackfn/*, that = undefined */){ var O = Object(assertDefined(this)) , that = arguments[1] , self = ES5Object(O) , f = ctx(callbackfn, that, 3) , length = toLength(self.length) , index = 0 , result = isMap ? Array(length) : isFilter ? [] : undefined , val, res; for(;length > index; index++)if(noholes || index in self){ val = self[index]; res = f(val, index, O); if(type){ if(isMap)result[index] = res; // 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(isEvery)return false; // every } } return isFindIndex ? -1 : isSome || isEvery ? isEvery : result; } } function createArrayContains(isContains){ return function(el /*, fromIndex = 0 */){ var O = ES5Object(assertDefined(this)) , length = toLength(O.length) , index = toIndex(arguments[1], length); if(isContains && el != el){ for(;length > index; index++)if(sameNaN(O[index]))return isContains || index; } else for(;length > index; index++)if(isContains || index in O){ if(O[index] === el)return isContains || index; } return !isContains && -1; } } function generic(A, B){ // strange IE quirks mode bug -> use typeof vs isFunction return typeof A == 'function' ? A : B; } // Math var MAX_SAFE_INTEGER = 0x1fffffffffffff // pow(2, 53) - 1 == 9007199254740991 , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min , random = Math.random , trunc = Math.trunc || function(it){ return (it > 0 ? floor : ceil)(it); } // 20.1.2.4 Number.isNaN(number) function sameNaN(number){ return number != number; } // 7.1.4 ToInteger function toInteger(it){ return isNaN(it) ? 0 : trunc(it); } // 7.1.15 ToLength function toLength(it){ return it > 0 ? min(toInteger(it), MAX_SAFE_INTEGER) : 0; } function toIndex(index, length){ var index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); } function createReplacer(regExp, replace, isStatic){ var replacer = isObject(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(isStatic ? it : this).replace(regExp, replacer); } } function createPointAt(toString){ return function(pos){ var s = String(assertDefined(this)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return toString ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? toString ? s.charAt(i) : a : toString ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; } } // Assertion & errors var REDUCE_ERROR = 'Reduce of empty object with no initial value'; function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } function assertDefined(it){ if(it == undefined)throw TypeError('Function called on null or undefined'); return it; } function assertFunction(it){ assert(isFunction(it), it, ' is not a function!'); return it; } function assertObject(it){ assert(isObject(it), it, ' is not an object!'); return it; } function assertInstance(it, Constructor, name){ assert(it instanceof Constructor, name, ": use the 'new' operator!"); } // Property descriptors & Symbol function descriptor(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value } } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return defineProperty(object, key, descriptor(bitmap, value)); } : simpleSet; } function uid(key){ return SYMBOL + '(' + key + ')_' + (++sid + random())[TO_STRING](36); } function getWellKnownSymbol(name, setter){ return (Symbol && Symbol[name]) || (setter ? Symbol : safeSymbol)(SYMBOL + DOT + name); } // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. var DESC = !!function(){try{return defineProperty({}, DOT, ObjectProto)}catch(e){}}() , sid = 0 , hidden = createDefiner(1) , set = Symbol ? simpleSet : hidden , safeSymbol = Symbol || uid; function assignHidden(target, src){ for(var key in src)hidden(target, key, src[key]); return target; } var SYMBOL_UNSCOPABLES = getWellKnownSymbol('unscopables') , ArrayUnscopables = ArrayProto[SYMBOL_UNSCOPABLES] || {}; // Iterators var SYMBOL_ITERATOR = getWellKnownSymbol(ITERATOR) , SYMBOL_TAG = getWellKnownSymbol(TO_STRING_TAG) , SUPPORT_FF_ITER = FF_ITERATOR in ArrayProto , ITER = safeSymbol('iter') , KEY = 1 , VALUE = 2 , Iterators = {} , IteratorPrototype = {} , NATIVE_ITERATORS = SYMBOL_ITERATOR in ArrayProto // Safari define byggy iterators w/o `next` , BUGGY_ITERATORS = 'keys' in ArrayProto && !('next' in [].keys()); // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, returnThis); function setIterator(O, value){ hidden(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol SUPPORT_FF_ITER && hidden(O, FF_ITERATOR, value); } function createIterator(Constructor, NAME, next, proto){ Constructor[PROTOTYPE] = create(proto || IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); } function defineIterator(Constructor, NAME, value, DEFAULT){ var proto = Constructor[PROTOTYPE] , iter = get(proto, SYMBOL_ITERATOR) || get(proto, FF_ITERATOR) || (DEFAULT && get(proto, DEFAULT)) || value; if(framework){ // Define iterator setIterator(proto, iter); if(iter !== value){ var iterProto = getPrototypeOf(iter.call(new Constructor)); // Set @@toStringTag to native iterators setToStringTag(iterProto, NAME + ' Iterator', true); // FF fix has(proto, FF_ITERATOR) && setIterator(iterProto, returnThis); } } // Plug for library Iterators[NAME] = iter; // FF & v8 fix Iterators[NAME + ' Iterator'] = returnThis; return iter; } function defineStdIterators(Base, NAME, Constructor, next, DEFAULT, IS_SET){ function createIter(kind){ return function(){ return new Constructor(this, kind); } } createIterator(Constructor, NAME, next); var entries = createIter(KEY+VALUE) , values = createIter(VALUE); if(DEFAULT == VALUE)values = defineIterator(Base, NAME, values, 'values'); else entries = defineIterator(Base, NAME, entries, 'entries'); if(DEFAULT){ $define(PROTO + FORCED * BUGGY_ITERATORS, NAME, { entries: entries, keys: IS_SET ? values : createIter(KEY), values: values }); } } function iterResult(done, value){ return {value: value, done: !!done}; } function isIterable(it){ var O = Object(it) , Symbol = global[SYMBOL] , hasExt = !!(Symbol && Symbol[ITERATOR] && Symbol[ITERATOR] in O); return hasExt || SYMBOL_ITERATOR in O || has(Iterators, classof(O)); } function getIterator(it){ var Symbol = global[SYMBOL] , ext = Symbol && Symbol[ITERATOR] && it[Symbol[ITERATOR]] , getIter = ext || it[SYMBOL_ITERATOR] || Iterators[classof(it)]; return assertObject(getIter.call(it)); } function stepCall(fn, value, entries){ return entries ? invoke(fn, value) : fn(value); } function forOf(iterable, entries, fn, that){ var iterator = getIterator(iterable) , f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done)if(stepCall(f, step.value, entries) === false)return; } // core var NODE = cof(process) == PROCESS , core = {} , path = framework ? global : core , old = global.core // type bitmap , FORCED = 1 , GLOBAL = 2 , STATIC = 4 , PROTO = 8 , BIND = 16 , WRAP = 32; function $define(type, name, source){ var key, own, out, exp , isGlobal = type & GLOBAL , target = isGlobal ? global : (type & STATIC) ? global[name] : (global[name] || ObjectProto)[PROTOTYPE] , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // there is a similar native own = !(type & FORCED) && target && key in target && (!isFunction(target[key]) || isNative(target[key])); // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context if(type & BIND && own)exp = ctx(out, global); // wrap global constructors for prevent change them in library else if(type & WRAP && !framework && target[key] == out){ exp = function(param){ return this instanceof out ? new out(param) : out(param); } exp[PROTOTYPE] = out[PROTOTYPE]; } else exp = type & PROTO && isFunction(out) ? ctx(call, out) : out; // export if(exports[key] != out)hidden(exports, key, exp); // extend global if(framework && target && !own){ if(isGlobal)target[key] = out; else delete target[key] && hidden(target, key, out); } } } // CommonJS export if(typeof module != 'undefined' && module.exports)module.exports = core; // RequireJS export if(isFunction(define) && define.amd)define(function(){return core}); // Export to global object if(!NODE || framework){ core.noConflict = function(){ global.core = old; return core; } global.core = core; } /****************************************************************************** * Module : es5 * ******************************************************************************/ // ECMAScript 5 shim !function(IS_ENUMERABLE, Empty, _classof, $PROTO){ if(!DESC){ getOwnDescriptor = function(O, P){ if(has(O, P))return descriptor(!ObjectProto[IS_ENUMERABLE].call(O, P), O[P]); }; defineProperty = function(O, P, Attributes){ if('value' in Attributes)assertObject(O)[P] = Attributes.value; return O; }; defineProperties = function(O, Properties){ assertObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P, Attributes; while(length > i){ P = keys[i++]; Attributes = Properties[P]; if('value' in Attributes)O[P] = Attributes.value; } return O; }; } $define(STATIC + FORCED * !DESC, OBJECT, { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: getOwnDescriptor, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: defineProperty, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = [CONSTRUCTOR, HAS_OWN, 'isPrototypeOf', IS_ENUMERABLE, TO_LOCALE, TO_STRING, 'valueOf'] // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', PROTOTYPE) , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype function createDict(){ // Thrash, waste and sodomy: IE GC bug var iframe = document[CREATE_ELEMENT]('iframe') , i = keysLen1 , iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); iframe.src = 'javascript:'; // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script>'); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][keys1[i]]; return createDict(); } function createGetKeys(names, length, isNames){ return function(object){ var O = ES5Object(assertDefined(object)) , i = 0 , result = [] , key; for(key in O)if(key != $PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~indexOf.call(result, key) || result.push(key); } return result; } } function isPrimitive(it){ return !isObject(it) } $define(STATIC, OBJECT, { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: getPrototypeOf = getPrototypeOf || function(O){ if(has(assertObject(O), $PROTO))return O[$PROTO]; if(isFunction(O[CONSTRUCTOR]) && O instanceof O[CONSTRUCTOR]){ return O[CONSTRUCTOR][PROTOTYPE]; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: getNames = getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: create = create || function(O, /*?*/Properties){ var result if(O !== null){ Empty[PROTOTYPE] = assertObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf shim if(result[CONSTRUCTOR][PROTOTYPE] !== O)result[$PROTO] = O; } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: getKeys = getKeys || createGetKeys(keys1, keysLen1, false), // 19.1.2.17 / 15.2.3.8 Object.seal(O) seal: returnIt, // <- cap // 19.1.2.5 / 15.2.3.9 Object.freeze(O) freeze: returnIt, // <- cap // 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O) preventExtensions: returnIt, // <- cap // 19.1.2.13 / 15.2.3.11 Object.isSealed(O) isSealed: isPrimitive, // <- cap // 19.1.2.12 / 15.2.3.12 Object.isFrozen(O) isFrozen: isPrimitive, // <- cap // 19.1.2.11 / 15.2.3.13 Object.isExtensible(O) isExtensible: isObject // <- cap }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $define(PROTO, FUNCTION, { bind: function(that /*, args... */){ var fn = assertFunction(this) , partArgs = slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(slice.call(arguments)); return (this instanceof bound ? construct : invoke)(fn, args, that); } return bound; } }); // Fix for not array-like ES3 string function arrayMethodFix(fn){ return function(){ return fn.apply(ES5Object(this), arguments); } } if(!(0 in Object(DOT) && DOT[0] == DOT)){ ES5Object = function(it){ return cof(it) == STRING ? it.split('') : Object(it); } slice = arrayMethodFix(slice); } $define(PROTO + FORCED * (ES5Object != Object), ARRAY, { slice: slice, join: arrayMethodFix(ArrayProto.join) }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $define(STATIC, ARRAY, { isArray: function(arg){ return cof(arg) == ARRAY } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assertFunction(callbackfn); var O = ES5Object(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(2 > arguments.length)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; assert(isRight ? index >= 0 : length > index, REDUCE_ERROR); } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; } } $define(PROTO, ARRAY, { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: forEach = forEach || createArrayMethod(0), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: createArrayMethod(1), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: createArrayMethod(2), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: createArrayMethod(3), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: createArrayMethod(4), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: indexOf = indexOf || createArrayContains(false), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = ES5Object(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = min(index, toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $define(PROTO, STRING, {trim: createReplacer(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $define(STATIC, DATE, {now: function(){ return +new Date; }}); if(_classof(function(){return arguments}()) == OBJECT)classof = function(it){ var cof = _classof(it); return cof == OBJECT && isFunction(it.callee) ? ARGUMENTS : cof; } }('propertyIsEnumerable', Function(), classof, safeSymbol(PROTOTYPE)); /****************************************************************************** * Module : global * ******************************************************************************/ $define(GLOBAL + FORCED, {global: global}); /****************************************************************************** * Module : es6_symbol * ******************************************************************************/ // ECMAScript 6 symbols shim !function(TAG, SymbolRegistry, setter){ // 19.4.1.1 Symbol([description]) if(!isNative(Symbol)){ Symbol = function(description){ assert(!(this instanceof Symbol), SYMBOL + ' is not a ' + CONSTRUCTOR); var tag = uid(description); DESC && setter && defineProperty(ObjectProto, tag, { configurable: true, set: function(value){ hidden(this, tag, value); } }); return set(create(Symbol[PROTOTYPE]), TAG, tag); } hidden(Symbol[PROTOTYPE], TO_STRING, function(){ return this[TAG]; }); } $define(GLOBAL + WRAP, {Symbol: Symbol}); var symbolStatics = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = Symbol(key); }, // 19.4.2.4 Symbol.iterator iterator: SYMBOL_ITERATOR, // 19.4.2.5 Symbol.keyFor(sym) keyFor: part.call(keyOf, SymbolRegistry), // 19.4.2.13 Symbol.toStringTag toStringTag: SYMBOL_TAG = getWellKnownSymbol(TO_STRING_TAG, true), // 19.4.2.14 Symbol.unscopables unscopables: SYMBOL_UNSCOPABLES, pure: safeSymbol, set: set, useSetter: function(){setter = true}, useSimple: function(){setter = false} }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.10 Symbol.species // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive forEach.call(array('hasInstance,isConcatSpreadable,match,replace,search,' + 'species,split,toPrimitive'), function(it){ symbolStatics[it] = getWellKnownSymbol(it); } ); $define(STATIC, SYMBOL, symbolStatics); setToStringTag(Symbol, SYMBOL); // 26.1.11 Reflect.ownKeys(target) $define(GLOBAL, {Reflect: {ownKeys: ownKeys}}); }(safeSymbol('tag'), {}, true); /****************************************************************************** * Module : es6 * ******************************************************************************/ // ECMAScript 6 shim !function(RegExpProto, isFinite, tmp){ var RangeError = global.RangeError // 20.1.2.3 Number.isInteger(number) , isInteger = Number.isInteger || function(it){ return !isObject(it) && isFinite(it) && floor(it) === it; } // 20.2.2.28 Math.sign(x) , sign = Math.sign || function sign(it){ return (it = +it) == 0 || it != it ? it : it < 0 ? -1 : 1; } , pow = Math.pow , abs = Math.abs , exp = Math.exp , log = Math.log , sqrt = Math.sqrt , fcc = String.fromCharCode , at = createPointAt(true); var objectStatic = { // 19.1.3.1 Object.assign(target, source) assign: assign, // 19.1.3.10 Object.is(value1, value2) is: function(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } }; // 19.1.3.19 Object.setPrototypeOf(O, proto) // Works with __proto__ only. Old v8 can't works with null proto objects. '__proto__' in ObjectProto && function(buggy, set){ try { set = ctx(call, getOwnDescriptor(ObjectProto, '__proto__').set, 2); set({}, ArrayProto); } catch(e){ buggy = true } objectStatic.setPrototypeOf = setPrototypeOf = setPrototypeOf || function(O, proto){ assertObject(O); assert(proto === null || isObject(proto), proto, ": can't set as prototype!"); if(buggy)O.__proto__ = proto; else set(O, proto); return O; } }(); $define(STATIC, OBJECT, objectStatic); // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } $define(STATIC, NUMBER, { // 20.1.2.1 Number.EPSILON EPSILON: pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function(it){ return typeof it == 'number' && isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: sameNaN, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); $define(STATIC, MATH, { // 20.2.2.3 Math.acosh(x) acosh: function(x){ return x < 1 ? NaN : log(x + sqrt(x * x - 1)); }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function(x){ return x == 0 ? +x : log((1 + +x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function(x){ return sign(x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32(x) clz32: function(x){ return (x >>>= 0) ? 32 - x[TO_STRING](2).length : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function(x){ return (exp(x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: function(x){ return x == 0 ? +x : x > -1e-6 && x < 1e-6 ? +x + x * x / 2 : exp(x) - 1; }, // 20.2.2.16 Math.fround(x) // TODO: fallback for IE9- fround: function(x){ return new Float32Array([x])[0]; }, // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) // TODO: work with very large & small numbers hypot: function(value1, value2){ var sum = 0 , length = arguments.length , value; while(length--){ value = +arguments[length]; if(value == Infinity || value == -Infinity)return Infinity; sum += value * value; } return sqrt(sum); }, // 20.2.2.18 Math.imul(x, y) imul: function(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); }, // 20.2.2.20 Math.log1p(x) log1p: function(x){ return x > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + +x); }, // 20.2.2.21 Math.log10(x) log10: function(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function(x){ return x == 0 ? +x : (exp(x) - exp(-x)) / 2; }, // 20.2.2.33 Math.tanh(x) tanh: function(x){ return isFinite(x) ? x == 0 ? +x : (exp(x) - exp(-x)) / (exp(x) + exp(-x)) : sign(x); }, // 20.2.2.34 Math.trunc(x) trunc: trunc }); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, MATH, true); function assertNotRegExp(it){ if(cof(it) == REGEXP)throw TypeError(); } $define(STATIC, STRING, { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function(x){ var res = [] , len = arguments.length , i = 0 , code while(len > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fcc(code) : fcc(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); }, // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function(callSite){ var raw = ES5Object(assertDefined(callSite.raw)) , len = toLength(raw.length) , sln = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(raw[i++])); if(i < sln)res.push(String(arguments[i])); } return res.join(''); } }); $define(PROTO, STRING, { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: createPointAt(false), // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) endsWith: function(searchString /*, endPosition = @length */){ assertNotRegExp(searchString); var that = String(assertDefined(this)) , endPosition = arguments[1] , len = toLength(that.length) , end = endPosition === undefined ? len : min(toLength(endPosition), len); searchString += ''; return that.slice(end - searchString.length, end) === searchString; }, // 21.1.3.7 String.prototype.includes(searchString, position = 0) includes: function(searchString /*, position = 0 */){ assertNotRegExp(searchString); return !!~String(assertDefined(this)).indexOf(searchString, arguments[1]); }, // 21.1.3.13 String.prototype.repeat(count) repeat: function(count){ var str = String(assertDefined(this)) , res = '' , n = toInteger(count); if(0 > n || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; }, // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function(searchString /*, position = 0 */){ assertNotRegExp(searchString); var that = String(assertDefined(this)) , index = toLength(min(arguments[1], that.length)); searchString += ''; return that.slice(index, index + searchString.length) === searchString; } }); // 21.1.3.27 String.prototype[@@iterator]() defineStdIterators(String, STRING, function(iterated){ set(this, ITER, {o: String(iterated), i: 0}); // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , index = iter.i , point; if(index >= O.length)return iterResult(1); point = at.call(O, index); iter.i += point.length; return iterResult(0, point); }); $define(STATIC, ARRAY, { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = Object(assertDefined(arrayLike)) , result = new (generic(this, Array)) , mapfn = arguments[1] , that = arguments[2] , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, that, 2) : undefined , index = 0 , length; if(isIterable(O))for(var iter = getIterator(O), step; !(step = iter.next()).done; index++){ result[index] = mapping ? f(step.value, index) : step.value; } else for(length = toLength(O.length); length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } result.length = index; return result; }, // 22.1.2.3 Array.of( ...items) of: function(/* ...args */){ var index = 0 , length = arguments.length , result = new (generic(this, Array))(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); $define(PROTO, ARRAY, { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) copyWithin: function(target /* = 0 */, start /* = 0, end = @length */){ var O = Object(assertDefined(this)) , len = toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments[2] , fin = end === undefined ? len : toIndex(end, len) , count = min(fin - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from = from + count - 1; to = to + count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; }, // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function(value /*, start = 0, end = @length */){ var O = Object(assertDefined(this)) , length = toLength(O.length) , index = toIndex(arguments[1], length) , end = arguments[2] , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; }, // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) find: createArrayMethod(5), // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) findIndex: createArrayMethod(6) }); // 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]() defineStdIterators(Array, ARRAY, function(iterated, kind){ set(this, ITER, {o: ES5Object(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , index = iter.i++; if(!O || index >= O.length)return iter.o = undefined, iterResult(1); if(kind == KEY) return iterResult(0, index); if(kind == VALUE)return iterResult(0, O[index]); return iterResult(0, [index, O[index]]); }, VALUE); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators[ARGUMENTS] = Iterators[ARRAY]; // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); function WrappedRegExp(pattern, flags){ return new RegExp(cof(pattern) == REGEXP && flags !== undefined ? pattern.source : pattern, flags); } function wrapObjectMethod(key, MODE){ var fn = Object[key]; try { fn(DOT) } catch(e){ Object[key] = MODE == 1 ? function(it){ return isObject(it) ? fn(it) : it } : MODE == 2 ? function(it){ return isObject(it) ? fn(it) : true } : MODE == 3 ? function(it){ return isObject(it) ? fn(it) : false } : MODE == 4 ? function(it, key){ return fn(Object(assertDefined(it)), key) } : function(it){ return fn(Object(assertDefined(it))) } } } if(framework){ // Object static methods accept primitives wrapObjectMethod('freeze', 1); wrapObjectMethod('seal', 1); wrapObjectMethod('preventExtensions', 1); wrapObjectMethod('isFrozen', 2); wrapObjectMethod('isSealed', 2); wrapObjectMethod('isExtensible', 3); wrapObjectMethod('getOwnPropertyDescriptor', 4); wrapObjectMethod('getPrototypeOf'); wrapObjectMethod('keys'); wrapObjectMethod('getOwnPropertyNames'); // 19.1.3.6 Object.prototype.toString() tmp[SYMBOL_TAG] = DOT; if(cof(tmp) != DOT)hidden(ObjectProto, TO_STRING, function(){ return '[object ' + classof(this) + ']'; }); // RegExp allows a regex with flags as the pattern if(DESC && !function(){try{return RegExp(/a/g, 'i') == '/a/i'}catch(e){}}()){ forEach.call(getNames(RegExp), function(key){ key in WrappedRegExp || defineProperty(WrappedRegExp, key, { configurable: true, get: function(){ return RegExp[key] }, set: function(it){ RegExp[key] = it } }); }); RegExpProto[CONSTRUCTOR] = WrappedRegExp; WrappedRegExp[PROTOTYPE] = RegExpProto; hidden(global, REGEXP, WrappedRegExp); } // 21.2.5.3 get RegExp.prototype.flags() if(/./g.flags != 'g')defineProperty(RegExpProto, 'flags', { configurable: true, get: createReplacer(/^.*\/(\w*)$/, '$1') }); // 22.1.3.31 Array.prototype[@@unscopables] forEach.call(array('find,findIndex,fill,copyWithin,entries,keys,values'), function(it){ ArrayUnscopables[it] = true; }); SYMBOL_UNSCOPABLES in ArrayProto || hidden(ArrayProto, SYMBOL_UNSCOPABLES, ArrayUnscopables); } }(RegExp[PROTOTYPE], isFinite, {}); /****************************************************************************** * Module : immediate * ******************************************************************************/ // setImmediate shim // Node.js 0.9+ & IE10+ has setImmediate, else: isFunction(setImmediate) && isFunction(clearImmediate) || function(ONREADYSTATECHANGE){ var postMessage = global.postMessage , addEventListener = global.addEventListener , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , defer, channel, port; setImmediate = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); } defer(counter); return counter; } clearImmediate = function(id){ delete queue[id]; } function run(id){ if(has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run(event.data); } // Node.js 0.8- if(NODE){ defer = function(id){ nextTick(part.call(run, id)); } // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); } addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } else if(document && ONREADYSTATECHANGE in document[CREATE_ELEMENT]('script')){ defer = function(id){ html.appendChild(document[CREATE_ELEMENT]('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run(id); } } // Rest old browsers } else { defer = function(id){ setTimeout(part.call(run, id), 0); } } }('onreadystatechange'); $define(GLOBAL + BIND, { setImmediate: setImmediate, clearImmediate: clearImmediate }); /****************************************************************************** * Module : es6_promise * ******************************************************************************/ // ES6 promises shim // Based on https://github.com/getify/native-promise-only/ !function(Promise, test){ isFunction(Promise) && isFunction(Promise.resolve) && Promise.resolve(test = new Promise(Function())) == test || function(asap, DEF){ function isThenable(o){ var then; if(isObject(o))then = o.then; return isFunction(then) ? then : false; } function notify(def){ var chain = def.chain; chain.length && asap(function(){ var msg = def.msg , ok = def.state == 1 , i = 0; while(chain.length > i)!function(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ ret = cb === true ? msg : cb(msg); if(ret === react.P){ react.rej(TypeError(PROMISE + '-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(msg); } catch(err){ react.rej(err); } }(chain[i++]); chain.length = 0; }); } function resolve(msg){ var def = this , then, wrapper; if(def.done)return; def.done = true; def = def.def || def; // unwrap try { if(then = isThenable(msg)){ wrapper = {def: def, done: false}; // wrap then.call(msg, ctx(resolve, wrapper, 1), ctx(reject, wrapper, 1)); } else { def.msg = msg; def.state = 1; notify(def); } } catch(err){ reject.call(wrapper || {def: def, done: false}, err); // wrap } } function reject(msg){ var def = this; if(def.done)return; def.done = true; def = def.def || def; // unwrap def.msg = msg; def.state = 2; notify(def); } // 25.4.3.1 Promise(executor) Promise = function(executor){ assertFunction(executor); assertInstance(this, Promise, PROMISE); var def = {chain: [], state: 0, done: false, msg: undefined}; hidden(this, DEF, def); try { executor(ctx(resolve, def, 1), ctx(reject, def, 1)); } catch(err){ reject.call(def, err); } } assignHidden(Promise[PROTOTYPE], { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function(onFulfilled, onRejected){ var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false } , P = react.P = new this[CONSTRUCTOR](function(resolve, reject){ react.res = assertFunction(resolve); react.rej = assertFunction(reject); }), def = this[DEF]; def.chain.push(react); def.state && notify(def); return P; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); assignHidden(Promise, { // 25.4.4.1 Promise.all(iterable) all: function(iterable){ var Promise = this , values = []; return new Promise(function(resolve, reject){ forOf(iterable, false, push, values); var remaining = values.length , results = Array(remaining); if(remaining)forEach.call(values, function(promise, index){ Promise.resolve(promise).then(function(value){ results[index] = value; --remaining || resolve(results); }, reject); }); else resolve(results); }); }, // 25.4.4.4 Promise.race(iterable) race: function(iterable){ var Promise = this; return new Promise(function(resolve, reject){ forOf(iterable, false, function(promise){ Promise.resolve(promise).then(resolve, reject); }); }); }, // 25.4.4.5 Promise.reject(r) reject: function(r){ return new this(function(resolve, reject){ reject(r); }); }, // 25.4.4.6 Promise.resolve(x) resolve: function(x){ return isObject(x) && getPrototypeOf(x) === this[PROTOTYPE] ? x : new this(function(resolve, reject){ resolve(x); }); } }); }(nextTick || setImmediate, safeSymbol('def')); setToStringTag(Promise, PROMISE); $define(GLOBAL + FORCED * !isNative(Promise), {Promise: Promise}); }(global[PROMISE]); /****************************************************************************** * Module : es6_collections * ******************************************************************************/ // ECMAScript 6 collections shim !function(){ var UID = safeSymbol('uid') , DATA = safeSymbol('data') , WEAK = safeSymbol('weak') , LAST = safeSymbol('last') , FIRST = safeSymbol('first') , SIZE = DESC ? safeSymbol('size') : 'size' , uid = 0; function getCollection(C, NAME, methods, commonMethods, isMap, isWeak){ var ADDER = isMap ? 'set' : 'add' , proto = C && C[PROTOTYPE] , O = {}; function initFromIterable(that, iterable){ if(iterable != undefined)forOf(iterable, isMap, that[ADDER], that); return that; } function fixSVZ(key, chain){ var method = proto[key]; framework && hidden(proto, key, function(a, b){ var result = method.call(this, a === 0 ? 0 : a, b); return chain ? this : result; }); } if(!isNative(C) || !(isWeak || (!BUGGY_ITERATORS && has(proto, 'entries')))){ // create collection constructor C = isWeak ? function(iterable){ assertInstance(this, C, NAME); set(this, UID, uid++); initFromIterable(this, iterable); } : function(iterable){ var that = this; assertInstance(that, C, NAME); set(that, DATA, create(null)); set(that, SIZE, 0); set(that, LAST, undefined); set(that, FIRST, undefined); initFromIterable(that, iterable); }; assignHidden(assignHidden(C[PROTOTYPE], methods), commonMethods); isWeak || defineProperty(C[PROTOTYPE], 'size', {get: function(){ return assertDefined(this[SIZE]); }}); } else { var Native = C , inst = new C , chain = inst[ADDER](isWeak ? {} : -0, 1) , buggyZero; // wrap to init collections from iterable if(!NATIVE_ITERATORS || !C.length){ C = function(iterable){ assertInstance(this, C, NAME); return initFromIterable(new Native, iterable); } C[PROTOTYPE] = proto; } isWeak || inst[FOR_EACH](function(val, key){ buggyZero = 1 / key === -Infinity; }); // fix converting -0 key to +0 if(buggyZero){ fixSVZ('delete'); fixSVZ('has'); isMap && fixSVZ('get'); } // + fix .add & .set for chaining if(buggyZero || chain !== inst)fixSVZ(ADDER, true); } setToStringTag(C, NAME); O[NAME] = C; $define(GLOBAL + WRAP + FORCED * !isNative(C), O); // 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 isWeak || defineStdIterators(C, NAME, function(iterated, kind){ set(this, ITER, {o: iterated, k: kind}); }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , entry = iter.l; while(entry && entry.r)entry = entry.p; if(!O || !(iter.l = entry = entry ? entry.n : O[FIRST]))return iter.o = undefined, iterResult(1); if(kind == KEY) return iterResult(0, entry.k); if(kind == VALUE)return iterResult(0, entry.v); return iterResult(0, [entry.k, entry.v]); }, isMap ? KEY+VALUE : VALUE, !isMap); return C; } function fastKey(it, create){ // return it with 'S' prefix if it's string or with 'P' prefix for over primitives if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; // if it hasn't object id - add next if(!has(it, UID)){ if(create)hidden(it, UID, ++uid); else return ''; } // return object id with 'O' prefix return 'O' + it[UID]; } function def(that, key, value){ var index = fastKey(key, true) , data = that[DATA] , last = that[LAST] , entry; if(index in data)data[index].v = value; else { entry = data[index] = {k: key, v: value, p: last}; if(!that[FIRST])that[FIRST] = entry; if(last)last.n = entry; that[LAST] = entry; that[SIZE]++; } return that; } function del(that, index){ var data = that[DATA] , entry = data[index] , next = entry.n , prev = entry.p; delete data[index]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that[FIRST] == entry)that[FIRST] = next; if(that[LAST] == entry)that[LAST] = prev; that[SIZE]--; } var collectionMethods = { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function(){ for(var index in this[DATA])del(this, index); }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var index = fastKey(key) , contains = index in this[DATA]; if(contains)del(this, index); return contains; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments[1], 3) , entry; while(entry = entry ? entry.n : this[FIRST]){ f(entry.v, entry.k, this); while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function(key){ return fastKey(key) in this[DATA]; } } // 23.1 Map Objects Map = getCollection(Map, MAP, { // 23.1.3.6 Map.prototype.get(key) get: function(key){ var entry = this[DATA][fastKey(key)]; return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function(key, value){ return def(this, key === 0 ? 0 : key, value); } }, collectionMethods, true); // 23.2 Set Objects Set = getCollection(Set, SET, { // 23.2.3.1 Set.prototype.add(value) add: function(value){ return def(this, value = value === 0 ? 0 : value, value); } }, collectionMethods); function setWeak(that, key, value){ has(assertObject(key), WEAK) || hidden(key, WEAK, {}); key[WEAK][that[UID]] = value; return that; } function hasWeak(key){ return isObject(key) && has(key, WEAK) && has(key[WEAK], this[UID]); } var weakMethods = { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ return hasWeak.call(this, key) && delete key[WEAK][this[UID]]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: hasWeak }; // 23.3 WeakMap Objects WeakMap = getCollection(WeakMap, WEAKMAP, { // 23.3.3.3 WeakMap.prototype.get(key) get: function(key){ if(isObject(key) && has(key, WEAK))return key[WEAK][this[UID]]; }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function(key, value){ return setWeak(this, key, value); } }, weakMethods, true, true); // 23.4 WeakSet Objects WeakSet = getCollection(WeakSet, WEAKSET, { // 23.4.3.1 WeakSet.prototype.add(value) add: function(value){ return setWeak(this, value, true); } }, weakMethods, false, true); }(); /****************************************************************************** * Module : es6_reflect * ******************************************************************************/ !function(){ function Enumerate(iterated){ var keys = [], key; for(key in iterated)keys.push(key); set(this, ITER, {o: iterated, a: keys, i: 0}); } createIterator(Enumerate, OBJECT, function(){ var iter = this[ITER] , keys = iter.a , key; do { if(iter.i >= keys.length)return iterResult(1); } while(!((key = keys[iter.i++]) in iter.o)); return iterResult(0, key); }); function wrap(fn){ return function(it){ assertObject(it); try { return fn.apply(undefined, arguments), true; } catch(e){ return false; } } } function reflectGet(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc = getOwnDescriptor(assertObject(target), propertyKey), proto; if(desc)return desc.get ? desc.get.call(receiver) : desc.value; return isObject(proto = getPrototypeOf(target)) ? reflectGet(proto, propertyKey, receiver) : undefined; } function reflectSet(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , desc = getOwnDescriptor(assertObject(target), propertyKey), proto; if(desc){ if(desc.writable === false)return false; if(desc.set)return desc.set.call(receiver, V), true; } if(isObject(proto = getPrototypeOf(target)))return reflectSet(proto, propertyKey, V, receiver); desc = getOwnDescriptor(receiver, propertyKey) || descriptor(0); desc.value = V; return defineProperty(receiver, propertyKey, desc), true; } var reflect = { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) apply: ctx(call, apply, 3), // 26.1.2 Reflect.construct(target, argumentsList) construct: construct, // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) defineProperty: wrap(defineProperty), // 26.1.4 Reflect.deleteProperty(target, propertyKey) deleteProperty: function(target, propertyKey){ var desc = getOwnDescriptor(assertObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; }, // 26.1.5 Reflect.enumerate(target) enumerate: function(target){ return new Enumerate(assertObject(target)); }, // 26.1.6 Reflect.get(target, propertyKey [, receiver]) get: reflectGet, // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) getOwnPropertyDescriptor: getOwnDescriptor, // 26.1.8 Reflect.getPrototypeOf(target) getPrototypeOf: getPrototypeOf, // 26.1.9 Reflect.has(target, propertyKey) has: function(target, propertyKey){ return propertyKey in target; }, // 26.1.10 Reflect.isExtensible(target) isExtensible: Object.isExtensible || function(target){ return !!assertObject(target); }, // 26.1.11 Reflect.ownKeys(target) ownKeys: ownKeys, // 26.1.12 Reflect.preventExtensions(target) preventExtensions: wrap(Object.preventExtensions || returnIt), // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) set: reflectSet } // 26.1.14 Reflect.setPrototypeOf(target, proto) if(setPrototypeOf)reflect.setPrototypeOf = function(target, proto){ return setPrototypeOf(assertObject(target), proto), true; }; $define(GLOBAL, {Reflect: {}}); $define(STATIC, 'Reflect', reflect); }(); /****************************************************************************** * Module : es7 * ******************************************************************************/ !function(){ $define(PROTO, ARRAY, { // https://github.com/domenic/Array.prototype.includes includes: createArrayContains(true) }); $define(PROTO, STRING, { // https://github.com/mathiasbynens/String.prototype.at at: createPointAt(true) }); function createObjectToArray(isEntries){ return function(object){ var O = ES5Object(object) , keys = getKeys(object) , length = keys.length , i = 0 , result = Array(length) , key; if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]]; else while(length > i)result[i] = O[keys[i++]]; return result; } } $define(STATIC, OBJECT, { // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-04/apr-9.md#51-objectentries-objectvalues values: createObjectToArray(false), entries: createObjectToArray(true) }); $define(STATIC, REGEXP, { // https://gist.github.com/kangax/9698100 escape: createReplacer(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); }(); /****************************************************************************** * Module : es7_refs * ******************************************************************************/ // https://github.com/zenparsing/es-abstract-refs !function(REFERENCE){ REFERENCE_GET = getWellKnownSymbol(REFERENCE+'Get', true); var REFERENCE_SET = getWellKnownSymbol(REFERENCE+SET, true) , REFERENCE_DELETE = getWellKnownSymbol(REFERENCE+'Delete', true); $define(STATIC, SYMBOL, { referenceGet: REFERENCE_GET, referenceSet: REFERENCE_SET, referenceDelete: REFERENCE_DELETE }); hidden(FunctionProto, REFERENCE_GET, returnThis); function setMapMethods(Constructor){ if(Constructor){ var MapProto = Constructor[PROTOTYPE]; hidden(MapProto, REFERENCE_GET, MapProto.get); hidden(MapProto, REFERENCE_SET, MapProto.set); hidden(MapProto, REFERENCE_DELETE, MapProto['delete']); } } setMapMethods(Map); setMapMethods(WeakMap); }('reference'); /****************************************************************************** * Module : dict * ******************************************************************************/ !function(DICT){ function Dict(iterable){ var dict = create(null); if(iterable != undefined){ if(isIterable(iterable)){ for(var iter = getIterator(iterable), step, value; !(step = iter.next()).done;){ value = step.value; dict[value[0]] = value[1]; } } else assign(dict, iterable); } return dict; } Dict[PROTOTYPE] = null; function DictIterator(iterated, kind){ set(this, ITER, {o: ES5Object(iterated), a: getKeys(iterated), i: 0, k: kind}); } createIterator(DictIterator, DICT, function(){ var iter = this[ITER] , O = iter.o , keys = iter.a , kind = iter.k , key; do { if(iter.i >= keys.length)return iterResult(1); } while(!has(O, key = keys[iter.i++])); if(kind == KEY) return iterResult(0, key); if(kind == VALUE)return iterResult(0, O[key]); return iterResult(0, [key, O[key]]); }); function createDictIter(kind){ return function(it){ return new DictIterator(it, kind); } } /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findKey * 7 -> mapPairs */ function createDictMethod(type){ var isMap = type == 1 , isEvery = type == 4; return function(object, callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = ES5Object(object) , result = isMap || type == 7 || type == 2 ? new (generic(this, Dict)) : undefined , key, val, res; for(key in O)if(has(O, key)){ val = O[key]; res = f(val, key, object); if(type){ if(isMap)result[key] = res; // map else if(res)switch(type){ case 2: result[key] = val; break // filter case 3: return true; // some case 5: return val; // find case 6: return key; // findKey case 7: result[res[0]] = res[1]; // mapPairs } else if(isEvery)return false; // every } } return type == 3 || isEvery ? isEvery : result; } } function createDictReduce(isTurn){ return function(object, mapfn, init){ assertFunction(mapfn); var O = ES5Object(object) , keys = getKeys(O) , length = keys.length , i = 0 , memo, key, result; if(isTurn)memo = init == undefined ? new (generic(this, Dict)) : Object(init); else if(arguments.length < 3){ assert(length, REDUCE_ERROR); memo = O[keys[i++]]; } else memo = Object(init); while(length > i)if(has(O, key = keys[i++])){ result = mapfn(memo, O[key], key, object); if(isTurn){ if(result === false)break; } else memo = result; } return memo; } } var findKey = createDictMethod(6); function includes(object, el){ return (el == el ? keyOf(object, el) : findKey(object, sameNaN)) !== undefined; } var dictMethods = { keys: createDictIter(KEY), values: createDictIter(VALUE), entries: createDictIter(KEY+VALUE), forEach: createDictMethod(0), map: createDictMethod(1), filter: createDictMethod(2), some: createDictMethod(3), every: createDictMethod(4), find: createDictMethod(5), findKey: findKey, mapPairs:createDictMethod(7), reduce: createDictReduce(false), turn: createDictReduce(true), keyOf: keyOf, includes:includes, // Has / get / set own property has: has, get: get, set: createDefiner(0), isDict: function(it){ return isObject(it) && getPrototypeOf(it) === Dict[PROTOTYPE]; } }; if(REFERENCE_GET)for(var key in dictMethods)!function(fn){ function method(){ for(var args = [this], i = 0; i < arguments.length;)args.push(arguments[i++]); return invoke(fn, args); } fn[REFERENCE_GET] = function(){ return method; } }(dictMethods[key]); $define(GLOBAL + FORCED, {Dict: assignHidden(Dict, dictMethods)}); }('Dict'); /****************************************************************************** * Module : $for * ******************************************************************************/ !function(ENTRIES, FN){ function $for(iterable, entries){ if(!(this instanceof $for))return new $for(iterable, entries); this[ITER] = getIterator(iterable); this[ENTRIES] = !!entries; } createIterator($for, 'Wrapper', function(){ return this[ITER].next(); }); var $forProto = $for[PROTOTYPE]; setIterator($forProto, function(){ return this[ITER]; // unwrap }); function createChainIterator(next){ function Iter(I, fn, that){ this[ITER] = getIterator(I); this[ENTRIES] = I[ENTRIES]; this[FN] = ctx(fn, that, I[ENTRIES] ? 2 : 1); } createIterator(Iter, 'Chain', next, $forProto); setIterator(Iter[PROTOTYPE], returnThis); // override $forProto iterator return Iter; } var MapIter = createChainIterator(function(){ var step = this[ITER].next(); return step.done ? step : iterResult(0, stepCall(this[FN], step.value, this[ENTRIES])); }); var FilterIter = createChainIterator(function(){ for(;;){ var step = this[ITER].next(); if(step.done || stepCall(this[FN], step.value, this[ENTRIES]))return step; } }); assignHidden($forProto, { of: function(fn, that){ forOf(this, this[ENTRIES], fn, that); }, array: function(fn, that){ var result = []; forOf(fn != undefined ? this.map(fn, that) : this, false, push, result); return result; }, filter: function(fn, that){ return new FilterIter(this, fn, that); }, map: function(fn, that){ return new MapIter(this, fn, that); } }); $for.isIterable = isIterable; $for.getIterator = getIterator; $define(GLOBAL + FORCED, {$for: $for}); }('entries', safeSymbol('fn')); /****************************************************************************** * Module : timers * ******************************************************************************/ // ie9- setTimeout & setInterval additional parameters fix !function(MSIE){ function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke(part, slice.call(arguments, 2), isFunction(fn) ? fn : Function(fn)), time); } : set; } $define(GLOBAL + BIND + FORCED * MSIE, { setTimeout: setTimeout = wrap(setTimeout), setInterval: wrap(setInterval) }); // ie9- dirty check }(!!navigator && /MSIE .\./.test(navigator.userAgent)); /****************************************************************************** * Module : binding * ******************************************************************************/ !function(_, toLocaleString){ // Placeholder core._ = path._ = path._ || {}; $define(PROTO + FORCED, FUNCTION, { part: part, by: function(that){ var fn = this , _ = path._ , holder = false , length = arguments.length , isThat = that === _ , i = +!isThat , indent = i , it, args; if(isThat){ it = fn; fn = call; } else it = that; if(length < 2)return ctx(fn, it, -1); args = Array(length - indent); while(length > i)if((args[i - indent] = arguments[i++]) === _)holder = true; return partial(fn, args, length, holder, _, true, it); }, only: function(numberArguments, that /* = @ */){ var fn = assertFunction(this) , n = toLength(numberArguments) , isThat = arguments.length > 1; return function(/* ...args */){ var length = min(n, arguments.length) , args = Array(length) , i = 0; while(length > i)args[i] = arguments[i++]; return invoke(fn, args, isThat ? that : this); } } }); function tie(key){ var that = this , bound = {}; return hidden(that, _, function(key){ if(key === undefined || !(key in that))return toLocaleString.call(that); return has(bound, key) ? bound[key] : (bound[key] = ctx(that[key], that, -1)); })[_](key); } hidden(path._, TO_STRING, function(){ return _; }); hidden(ObjectProto, _, tie); DESC || hidden(ArrayProto, _, tie); // IE8- dirty hack - redefined toLocaleString is not enumerable }(DESC ? uid('tie') : TO_LOCALE, ObjectProto[TO_LOCALE]); /****************************************************************************** * Module : object * ******************************************************************************/ !function(){ function define(target, mixin){ var keys = ownKeys(ES5Object(mixin)) , length = keys.length , i = 0, key; while(length > i)defineProperty(target, key = keys[i++], getOwnDescriptor(mixin, key)); return target; }; $define(STATIC + FORCED, OBJECT, { isObject: isObject, classof: classof, define: define, make: function(proto, mixin){ return define(create(proto), mixin); } }); }(); /****************************************************************************** * Module : array * ******************************************************************************/ $define(PROTO + FORCED, ARRAY, { turn: function(fn, target /* = [] */){ assertFunction(fn); var memo = target == undefined ? [] : Object(target) , O = ES5Object(this) , length = toLength(O.length) , index = 0; while(length > index)if(fn(memo, O[index], index++, this) === false)break; return memo; } }); if(framework)ArrayUnscopables.turn = true; /****************************************************************************** * Module : array_statics * ******************************************************************************/ // JavaScript 1.6 / Strawman array statics shim !function(arrayStatics){ function setArrayStatics(keys, length){ forEach.call(array(keys), function(key){ if(key in ArrayProto)arrayStatics[key] = ctx(call, ArrayProto[key], length); }); } setArrayStatics('pop,reverse,shift,keys,values,entries', 1); setArrayStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3); setArrayStatics('join,slice,concat,push,splice,unshift,sort,lastIndexOf,' + 'reduce,reduceRight,copyWithin,fill,turn'); $define(STATIC, ARRAY, arrayStatics); }({}); /****************************************************************************** * Module : number * ******************************************************************************/ !function(numberMethods){ function NumberIterator(iterated){ set(this, ITER, {l: toLength(iterated), i: 0}); } createIterator(NumberIterator, NUMBER, function(){ var iter = this[ITER] , i = iter.i++; return i < iter.l ? iterResult(0, i) : iterResult(1); }); defineIterator(Number, NUMBER, function(){ return new NumberIterator(this); }); numberMethods.random = function(lim /* = 0 */){ var a = +this , b = lim == undefined ? 0 : +lim , m = min(a, b); return random() * (max(a, b) - m) + m; }; forEach.call(array( // ES3: 'round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,' + // ES6: 'acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc' ), function(key){ var fn = Math[key]; if(fn)numberMethods[key] = function(/* ...args */){ // ie9- dont support strict mode & convert `this` to object -> convert it to number var args = [+this] , i = 0; while(arguments.length > i)args.push(arguments[i++]); return invoke(fn, args); } } ); $define(PROTO + FORCED, NUMBER, numberMethods); }({}); /****************************************************************************** * Module : string * ******************************************************************************/ !function(){ var escapeHTMLDict = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }, unescapeHTMLDict = {}, key; for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]] = key; $define(PROTO + FORCED, STRING, { escapeHTML: createReplacer(/[&<>"']/g, escapeHTMLDict), unescapeHTML: createReplacer(/&(?:amp|lt|gt|quot|apos);/g, unescapeHTMLDict) }); }(); /****************************************************************************** * Module : date * ******************************************************************************/ !function(formatRegExp, flexioRegExp, locales, current, SECONDS, MINUTES, HOURS, MONTH, YEAR){ function createFormat(prefix){ return function(template, locale /* = current */){ var that = this , dict = locales[has(locales, locale) ? locale : current]; function get(unit){ return that[prefix + unit](); } return String(template).replace(formatRegExp, function(part){ switch(part){ case 's' : return get(SECONDS); // Seconds : 0-59 case 'ss' : return lz(get(SECONDS)); // Seconds : 00-59 case 'm' : return get(MINUTES); // Minutes : 0-59 case 'mm' : return lz(get(MINUTES)); // Minutes : 00-59 case 'h' : return get(HOURS); // Hours : 0-23 case 'hh' : return lz(get(HOURS)); // Hours : 00-23 case 'D' : return get(DATE); // Date : 1-31 case 'DD' : return lz(get(DATE)); // Date : 01-31 case 'W' : return dict[0][get('Day')]; // Day : Понедельник case 'N' : return get(MONTH) + 1; // Month : 1-12 case 'NN' : return lz(get(MONTH) + 1); // Month : 01-12 case 'M' : return dict[2][get(MONTH)]; // Month : Январь case 'MM' : return dict[1][get(MONTH)]; // Month : Января case 'Y' : return get(YEAR); // Year : 2014 case 'YY' : return lz(get(YEAR) % 100); // Year : 14 } return part; }); } } function lz(num){ return num > 9 ? num : '0' + num; } function addLocale(lang, locale){ function split(index){ var result = []; forEach.call(array(locale.months), function(it){ result.push(it.replace(flexioRegExp, '$' + index)); }); return result; } locales[lang] = [array(locale.weekdays), split(1), split(2)]; return core; } $define(PROTO + FORCED, DATE, { format: createFormat('get'), formatUTC: createFormat('getUTC') }); addLocale(current, { weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday', months: 'January,February,March,April,May,June,July,August,September,October,November,December' }); addLocale('ru', { weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота', months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,' + 'Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь' }); core.locale = function(locale){ return has(locales, locale) ? current = locale : current; }; core.addLocale = addLocale; }(/\b\w\w?\b/g, /:(.*)\|(.*)$/, {}, 'en', 'Seconds', 'Minutes', 'Hours', 'Month', 'FullYear'); /****************************************************************************** * Module : console * ******************************************************************************/ !function(console, enabled){ var _console = { enable: function(){ enabled = true }, disable: function(){ enabled = false } }; // Methods from: // https://github.com/DeveloperToolsWG/console-object/blob/master/api.md // https://developer.mozilla.org/en-US/docs/Web/API/console forEach.call(array('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,isIndependentlyComposed,log,markTimeline,profile,' + 'profileEnd,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn'), function(key){ var fn = console[key]; _console[key] = function(){ if(enabled && fn)return apply.call(fn, console, arguments); }; } ); // console methods in some browsers are not configurable try { framework && delete global.console; } catch(e){} $define(GLOBAL + FORCED, {console: _console}); }(global.console || {}, true); }(Function('return this'), false);
fields/types/boolean/BooleanColumn.js
dryna/keystone-twoje-urodziny
import React from 'react'; import Checkbox from '../../components/Checkbox'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var BooleanColumn = React.createClass({ displayName: 'BooleanColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { return ( <ItemsTableValue truncate={false} field={this.props.col.type}> <Checkbox readonly checked={this.props.data.fields[this.props.col.path]} /> </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = BooleanColumn;
Libraries/Components/Touchable/TouchableOpacity.js
luqin/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule TouchableOpacity * @noflow */ 'use strict'; // Note (avik): add @flow when Flow supports spread properties in propTypes var Animated = require('Animated'); var NativeMethodsMixin = require('NativeMethodsMixin'); var React = require('React'); var TimerMixin = require('react-timer-mixin'); var Touchable = require('Touchable'); var TouchableWithoutFeedback = require('TouchableWithoutFeedback'); var ensurePositiveDelayProps = require('ensurePositiveDelayProps'); var flattenStyle = require('flattenStyle'); type Event = Object; var PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; /** * A wrapper for making views respond properly to touches. * On press down, the opacity of the wrapped view is decreased, dimming it. * This is done without actually changing the view hierarchy, and in general is * easy to add to an app without weird side-effects. * * Example: * * ``` * renderButton: function() { * return ( * <TouchableOpacity onPress={this._onPressButton}> * <Image * style={styles.button} * source={require('image!myButton')} * /> * </TouchableOpacity> * ); * }, * ``` */ var TouchableOpacity = React.createClass({ mixins: [TimerMixin, Touchable.Mixin, NativeMethodsMixin], propTypes: { ...TouchableWithoutFeedback.propTypes, /** * Determines what the opacity of the wrapped view should be when touch is * active. Defaults to 0.2. */ activeOpacity: React.PropTypes.number, }, getDefaultProps: function() { return { activeOpacity: 0.2, }; }, getInitialState: function() { return { ...this.touchableGetInitialState(), anim: new Animated.Value(1), }; }, componentDidMount: function() { ensurePositiveDelayProps(this.props); }, componentWillReceiveProps: function(nextProps) { ensurePositiveDelayProps(nextProps); }, /** * Animate the touchable to a new opacity. */ setOpacityTo: function(value: number) { Animated.timing( this.state.anim, {toValue: value, duration: 150} ).start(); }, /** * `Touchable.Mixin` self callbacks. The mixin will invoke these if they are * defined on your component. */ touchableHandleActivePressIn: function(e: Event) { this.clearTimeout(this._hideTimeout); this._hideTimeout = null; this._opacityActive(); this.props.onPressIn && this.props.onPressIn(e); }, touchableHandleActivePressOut: function(e: Event) { if (!this._hideTimeout) { this._opacityInactive(); } this.props.onPressOut && this.props.onPressOut(e); }, touchableHandlePress: function(e: Event) { this.clearTimeout(this._hideTimeout); this._opacityActive(); this._hideTimeout = this.setTimeout( this._opacityInactive, this.props.delayPressOut || 100 ); this.props.onPress && this.props.onPress(e); }, touchableHandleLongPress: function(e: Event) { this.props.onLongPress && this.props.onLongPress(e); }, touchableGetPressRectOffset: function() { return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET; }, touchableGetHitSlop: function() { return this.props.hitSlop; }, touchableGetHighlightDelayMS: function() { return this.props.delayPressIn || 0; }, touchableGetLongPressDelayMS: function() { return this.props.delayLongPress === 0 ? 0 : this.props.delayLongPress || 500; }, touchableGetPressOutDelayMS: function() { return this.props.delayPressOut; }, _opacityActive: function() { this.setOpacityTo(this.props.activeOpacity); }, _opacityInactive: function() { this.clearTimeout(this._hideTimeout); this._hideTimeout = null; var childStyle = flattenStyle(this.props.style) || {}; this.setOpacityTo( childStyle.opacity === undefined ? 1 : childStyle.opacity ); }, render: function() { return ( <Animated.View accessible={true} accessibilityLabel={this.props.accessibilityLabel} accessibilityComponentType={this.props.accessibilityComponentType} accessibilityTraits={this.props.accessibilityTraits} style={[this.props.style, {opacity: this.state.anim}]} testID={this.props.testID} onLayout={this.props.onLayout} hitSlop={this.props.hitSlop} onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder} onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest} onResponderGrant={this.touchableHandleResponderGrant} onResponderMove={this.touchableHandleResponderMove} onResponderRelease={this.touchableHandleResponderRelease} onResponderTerminate={this.touchableHandleResponderTerminate}> {this.props.children} {Touchable.renderDebugView({color: 'cyan', hitSlop: this.props.hitSlop})} </Animated.View> ); }, }); module.exports = TouchableOpacity;
src/test/__tests__/MetaMatchers-test.js
bhamodi/react
/** * 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. * * @emails react-core */ 'use strict'; var MetaMatchers = require('MetaMatchers'); describe('meta-matchers', function() { beforeEach(function() { this.addMatchers(MetaMatchers); }); function a() { it('should add 1 and 2', function() { expect(1 + 2).toBe(3); }); } function b() { it('should add 1 and 2', function() { expect(1 + 2).toBe(3); }); } function c() { it('should add 1 and 2', function() { expect(1 + 2).toBe(3); }); it('should mutiply 1 and 2', function() { expect(1 * 2).toBe(2); }); } function d() { it('should add 1 and 2', function() { expect(1 + 2).toBe(3); }); it('should mutiply 1 and 2', function() { expect(1 * 2).toBe(2); expect(2 * 1).toBe(2); }); } it('tests equality of specs', function() { expect(a).toEqualSpecsIn(b); }); it('tests inequality of specs and expects', function() { expect(b).not.toEqualSpecsIn(c); expect(c).not.toEqualSpecsIn(d); }); });
src/pages/community/section/others/Others.js
HeliumLau/Hoop-react
import React from 'react'; import Part from 'components/Part' export default class Others extends React.Component { render() { const list = [ { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212, route: '/news' }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12, route: '/more' }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212 }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212 }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212 }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212 }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212 }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212 }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212 }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212 }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212 }, { icon: 'icon-rocket', name: '休斯顿火箭队', num: 12212 } ] return ( <div> <Part list={list}/> </div> ) } }
packages/material-ui-icons/src/BrokenImageOutlined.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="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5v-4.58l.99.99 4-4 4 4 4-3.99L19 12.43V19zm0-9.41l-1.01-1.01-4 4.01-4-4-4 4-.99-1V5h14v4.59z" /></g></React.Fragment> , 'BrokenImageOutlined');
packages/material-ui-icons/src/LinkOff.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M17 7h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1 0 1.43-.98 2.63-2.31 2.98l1.46 1.46C20.88 15.61 22 13.95 22 12c0-2.76-2.24-5-5-5zm-1 4h-2.19l2 2H16zM2 4.27l3.11 3.11C3.29 8.12 2 9.91 2 12c0 2.76 2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1 0-1.59 1.21-2.9 2.76-3.07L8.73 11H8v2h2.73L13 15.27V17h1.73l4.01 4L20 19.74 3.27 3 2 4.27z" /><path fill="none" d="M0 24V0" /></React.Fragment> , 'LinkOff');
src/demo/foam/build/foam.js
gabrielmancini/interactor
/** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ if ( navigator && navigator.userAgent.indexOf('Firefox') != -1 ) { console.log('Loading Firefox Support.'); Object.defineProperties(MouseEvent.prototype, { offsetX: { get: function() { return this.clientX - this.target.getBoundingClientRect().left; } }, offsetY: { get: function() { return this.clientY - this.target.getBoundingClientRect().top; } } }); } /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ if ( ! Number.name ) { console.log('Polyfilling Function.prototype.name'); Object.defineProperty(Function.prototype, 'name', { get: function() { var text = this.toString(); return text.substring(text.indexOf('function') + 9, text.indexOf('(')).trim(); }, configurable: true, enumerable: true }); } /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ if (navigator && navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) { console.log('Loading Safari Support.'); (function(){ // prepare base perf object if (typeof window.performance === 'undefined') { window.performance = {}; } if (!window.performance.now){ var nowOffset = Date.now(); if (performance.timing && performance.timing.navigationStart){ nowOffset = performance.timing.navigationStart } window.performance.now = function now(){ return Date.now() - nowOffset; } } })(); // Number.isFinite polyfill // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite if (typeof Number.isFinite !== 'function') { Number.isFinite = function isFinite(value) { // 1. If Type(number) is not Number, return false. if (typeof value !== 'number') { return false; } // 2. If number is NaN, +∞, or −∞, return false. if (value !== value || value === Infinity || value === -Infinity) { return false; } // 3. Otherwise, return true. return true; }; } if ( typeof Number.isNaN !== 'function' ) { Number.isNaN = function(value) { return typeof value === "number" && value !== value; }; } } /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ var LANGUAGE = "en"; if ( navigator && navigator.language ) LANGUAGE = navigator.language; (function() { var m = /[?&]hl=([^&]*)/.exec(window.location.search); if ( m ) { LANGUAGE = m[1]; } var a = LANGUAGE.split('-'); LANGUAGE = []; var ls = []; for ( var i = a.length-1 ; i >= 0 ; i-- ) { LANGUAGE.push(a.slice(0, i+1).join('-')); } if ( LANGUAGE[LANGUAGE.length-1] !== 'en' ) LANGUAGE.push('en'); })(); /* console.log('Navigator.language: ', navigator.language); console.log('Location: ', window.location.search); console.log('LANGUAGE: ', LANGUAGE); */ function lm(m) { for ( var i = 0 ; i < LANGUAGE.length ; i++ ) if ( m.hasOwnProperty(LANGUAGE[i]) ) return m[LANGUAGE[i]]; console.log('No language match for: ', m); } /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ var DEBUG = DEBUG || false; var GLOBAL = GLOBAL || this; Object.defineProperty_ = Object.defineProperty; Object.defineProperty = function() { this.defineProperty_.apply(this, arguments); }; function MODEL(model) { var proto; function defineProperty(proto, key, map) { if ( ! map.value || proto === Object.prototype || proto === Array.prototype ) Object.defineProperty_.apply(this, arguments); else proto[key] = map.value; } if ( model.name ) { if ( ! GLOBAL[model.name] ) { if ( model.extendsModel ) { GLOBAL[model.name] = { __proto__: GLOBAL[model.extendsModel] }; } else { GLOBAL[model.name] = {}; } } proto = GLOBAL[model.name]; } else { proto = model.extendsProto ? GLOBAL[model.extendsProto].prototype : GLOBAL[model.extendsObject] ; } if ( model.properties ) for ( var i = 0 ; i < model.properties.length ; i++ ) { var p = model.properties[i]; defineProperty( proto, p.name, { get: p.getter, enumerable: false }); } for ( key in model.constants ) defineProperty( proto, key, { value: model.constants[key], writable: true, enumerable: false }); if ( Array.isArray(model.methods) ) { for ( var i = 0 ; i < model.methods.length ; i++ ) { var m = model.methods[i]; defineProperty( proto, m.name, { value: m, writable: true, enumerable: false }); } } else { for ( var key in model.methods ) defineProperty( proto, key, { value: model.methods[key], writable: true, enumerable: false }); } } var MODEL0 = MODEL; MODEL({ extendsObject: 'GLOBAL', methods: [ function memoize(f) { var cache = {}; var g = function() { var key = argsToArray(arguments).toString(); if ( ! cache.hasOwnProperty(key) ) cache[key] = f.apply(this, arguments); return cache[key]; }; g.name = f.name; return g; }, function memoize1(f) { /** Faster version of memoize() when only dealing with one argument. **/ var cache = {}; var g = function(arg) { var key = arg ? arg.toString() : ''; if ( ! cache.hasOwnProperty(key) ) cache[key] = f.call(this, arg); return cache[key]; }; g.name = f.name; return g; }, function constantFn(v) { /* Create a function which always returns the supplied constant value. */ return function() { return v; }; }, function latchFn(f) { var tripped = false; var val; /* Create a function which always returns the supplied constant value. */ return function() { if ( ! tripped ) { tripped = true; val = f(); f = undefined; } return val; }; }, function argsToArray(args) { var array = new Array(args.length); for ( var i = 0; i < args.length; i++ ) array[i] = args[i]; return array; }, function StringComparator(s1, s2) { if ( s1 == s2 ) return 0; return s1 < s2 ? -1 : 1; }, function equals(a, b) { if ( a === b ) return true; if ( ! a || ! b ) return false; if ( a.equals ) return a.equals(b); return a == b; }, function toCompare(c) { if ( Array.isArray(c) ) return CompoundComparator.apply(null, c); return c.compare ? c.compare.bind(c) : c; }, function CompoundComparator() { var args = argsToArray(arguments); var cs = []; // Convert objects with .compare() methods to compare functions. for ( var i = 0 ; i < args.length ; i++ ) cs[i] = toCompare(args[i]); var f = function(o1, o2) { for ( var i = 0 ; i < cs.length ; i++ ) { var r = cs[i](o1, o2); if ( r != 0 ) return r; } return 0; }; f.toSQL = function() { return args.map(function(s) { return s.toSQL(); }).join(','); }; f.toMQL = function() { return args.map(function(s) { return s.toMQL(); }).join(' '); }; f.toBQL = function() { return args.map(function(s) { return s.toBQL(); }).join(' '); }; f.toString = f.toSQL; return f; }, function randomAct() { /** * Take an array where even values are weights and odd values are functions, * and execute one of the functions with propability equal to it's relative * weight. */ // TODO: move this method somewhere better var totalWeight = 0.0; for ( var i = 0 ; i < arguments.length ; i += 2 ) totalWeight += arguments[i]; var r = Math.random(); for ( var i = 0, weight = 0 ; i < arguments.length ; i += 2 ) { weight += arguments[i]; if ( r <= weight / totalWeight ) { arguments[i+1](); return; } } }, // Workaround for crbug.com/258552 function Object_forEach(obj, fn) { for ( var key in obj ) if ( obj.hasOwnProperty(key) ) fn(obj[key], key); }, function predicatedSink(predicate, sink) { if ( predicate === TRUE || ! sink ) return sink; return { __proto__: sink, $UID: sink.$UID, put: function(obj, s, fc) { if ( sink.put && ( ! obj || predicate.f(obj) ) ) sink.put(obj, s, fc); }, remove: function(obj, s, fc) { if ( sink.remove && ( ! obj || predicate.f(obj) ) ) sink.remove(obj, s, fc); }, reset: function() { sink.reset(); }, toString: function() { return 'PredicatedSink(' + sink.$UID + ', ' + predicate + ', ' + sink + ')'; } }; }, function limitedSink(count, sink) { var i = 0; return { __proto__: sink, $UID: sink.$UID, put: function(obj, s, fc) { if ( i++ >= count && fc ) { fc.stop(); } else { sink.put(obj, s, fc); } }/*, eof: function() { sink.eof && sink.eof(); }*/ }; }, function skipSink(skip, sink) { var i = 0; return { __proto__: sink, $UID: sink.$UID, put: function(obj, s, fc) { if ( i++ >= skip ) sink.put(obj, s, fc); } }; }, function orderedSink(comparator, sink) { comparator = toCompare(comparator); return { __proto__: sink, $UID: sink.$UID, i: 0, arr: [], put: function(obj, s, fc) { this.arr.push(obj); }, eof: function() { this.arr.sort(comparator); this.arr.select(sink); } }; }, function defineLazyProperty(target, name, definitionFn) { Object.defineProperty(target, name, { get: function() { var definition = definitionFn.call(this); Object.defineProperty(this, name, definition); return definition.get ? definition.get.call(this) : definition.value; }, configurable: true }); }, // Function for returning multi-line strings from commented functions. // Ex. var str = multiline(function() { /* multi-line string here */ }); function multiline(f) { var s = f.toString(); var start = s.indexOf('/*'); var end = s.lastIndexOf('*/'); return s.substring(start+2, end); }, // Computes the XY coordinates of the given node // relative to the containing elements. // TODO: findViewportXY works better... but do we need to find parent? function findPageXY(node) { var x = 0; var y = 0; var parent; while ( node ) { parent = node; x += node.offsetLeft; y += node.offsetTop; node = node.offsetParent; } return [x, y, parent]; }, // Computes the XY coordinates of the given node // relative to the viewport. function findViewportXY(node) { var rect = node.getBoundingClientRect(); return [rect.left, rect.top]; }, function nop() { /** NOP function. **/ }, function stringtoutf8(str) { var res = []; for (var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); var count = 0; if ( code < 0x80 ) { res.push(code); continue; } // while(code > (0x40 >> count)) { // res.push(code & 0x3f); // count++; // code = code >> 7; // } // var header = 0x80 >> count; // res.push(code | header) } return res; }, function createGUID() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } ] }); var labelize = memoize1(function(str) { return capitalize(str.replace(/[a-z][A-Z]/g, function (a) { return a.charAt(0) + ' ' + a.charAt(1); })); }); var constantize = memoize1(function(str) { // switchFromCamelCaseToConstantFormat to SWITCH_FROM_CAMEL_CASE_TO_CONSTANT_FORMAT // TODO: add property to specify constantization. For now catch special case to avoid conflict with context this.X and this.Y. if ( str === 'x' ) return 'X_'; if ( str === 'y' ) return 'Y_'; return str.replace(/[a-z_][^0-9a-z_]/g, function(a) { return a.substring(0,1) + '_' + a.substring(1,2); }).toUpperCase(); }); var capitalize = memoize1(function(str) { // switchFromProperyName to //SwitchFromPropertyName return str[0].toUpperCase() + str.substring(1); }); MODEL({ extendsProto: 'Object', properties: [ { name: '$UID', getter: (function() { var id = 1; return function() { if ( Object.hasOwnProperty.call(this, '$UID__') ) return this.$UID__; this.$UID__ = id; id++; return this.$UID__; }; })() } ], methods: [ function become(other) { var local = Object.getOwnPropertyNames(this); for ( var i = 0; i < local.length; i++ ) { delete this[local[i]]; } var remote = Object.getOwnPropertyNames(other); for ( i = 0; i < remote.length; i++ ) { Object.defineProperty( this, remote[i], Object.getOwnPropertyDescriptor(other, remote[i])); } this.__proto__ = other.__proto__; } ] }); MODEL({ extendsProto: 'Array', constants: { oldForEach_: Array.prototype.forEach }, methods: [ function clone() { return this.slice(); }, function deepClone() { var a = this.clone(); for ( var i = 0 ; i < a.length ; i++ ) { var o = a[i]; if ( o && o.deepClone ) a[i] = o.deepClone(); } return a; }, function forEach(f, opt_this) { /* Replace Array.forEach with a faster version. */ if ( ! this || ! f || opt_this ) return this.oldForEach_.call(this, f, opt_this); var l = this.length; for ( var i = 0 ; i < l ; i++ ) f(this[i], i, this); }, function diff(other) { var added = other.slice(0); var removed = []; for ( var i = 0 ; i < this.length ; i++ ) { for ( var j = 0 ; j < added.length ; j++ ) { if ( this[i].compareTo(added[j]) == 0 ) { added.splice(j, 1); j--; break; } } if ( j == added.length ) removed.push(this[i]); } return { added: added, removed: removed }; }, function binaryInsert(item) { /* binaryInsert into a sorted array, removing duplicates */ var start = 0; var end = this.length-1; while ( end >= start ) { var m = start + Math.floor((end-start) / 2); var c = item.compareTo(this[m]); if ( c == 0 ) return this; // already there, nothing to do if ( c < 0 ) { end = m-1; } else { start = m+1; } } this.splice(start, 0, item); return this; }, function union(other) { return this.concat( other.filter(function(o) { return this.indexOf(o) == -1; }.bind(this))); }, function intersection(other) { return this.filter(function(o) { return other.indexOf(o) != -1; }); }, function intern() { for ( var i = 0 ; i < this.length ; i++ ) if ( this[i].intern ) this[i] = this[i].intern(); return this; }, function compareTo(other) { if ( this.length !== other.length ) return -1; for ( var i = 0 ; i < this.length ; i++ ) { var result = this[i].compareTo(other[i]); if ( result !== 0 ) return result; } return 0; }, function fReduce(comparator, arr) { compare = toCompare(comparator); var result = []; var i = 0; var j = 0; var k = 0; while ( i < this.length && j < arr.length ) { var a = compare(this[i], arr[j]); if ( a < 0 ) { result[k++] = this[i++]; continue; } if ( a == 0) { result[k++] = this[i++]; result[k++] = arr[j++]; continue; } result[k++] = arr[j++]; } if ( i != this.length ) result = result.concat(this.slice(i)); if ( j != arr.length ) result = result.concat(arr.slice(j)); return result; }, function pushAll(arr) { /** * Push an array of values onto an array. * @param arr array of values * @return new length of this array */ // TODO: not needed, port and replace with pipe() this.push.apply(this, arr); return this.length; }, function mapFind(map) { /** * Search for a single element in an array. * @param predicate used to determine element to find */ for ( var i = 0 ; i < this.length ; i++ ) { var result = map(this[i], i); if ( result ) return result; } }, function mapProp(prop) { // Called like myArray.mapProp('name'), that's equivalent to: // myArray.map(function(x) { return x.name; }); return this.map(function(x) { return x[prop]; }); }, function mapCall() { var args = Array.prototype.slice.call(arguments, 0); var func = args.shift(); return this.map(function(x) { return x[func] && x[func].apply(x[func], args); }); } ], properties: [ { name: 'memento', getter: function() { throw "Array's can not be memorized properly as a memento."; } } ] }); MODEL({ extendsProto: 'String', methods: [ function indexOfIC(a) { return ( a.length > this.length ) ? -1 : this.toUpperCase().indexOf(a.toUpperCase()); }, function equals(other) { return this.compareTo(other) === 0; }, function equalsIC(other) { return other && this.toUpperCase() === other.toUpperCase(); }, // deprecated, use global instead function capitalize() { return this.charAt(0).toUpperCase() + this.slice(1); }, // deprecated, use global instead function labelize() { return this.replace(/[a-z][A-Z]/g, function (a) { return a.charAt(0) + ' ' + a.charAt(1); }).capitalize(); }, function compareTo(o) { return ( o == this ) ? 0 : this < o ? -1 : 1; }, // Polyfil String.prototype.startsWith || function startsWith(a) { // This implementation is very slow for some reason return 0 == this.lastIndexOf(a, 0); }, function startsWithIC(a) { if ( a.length > this.length ) return false; var l = a.length; for ( var i = 0 ; i < l; i++ ) { if ( this[i].toUpperCase() !== a[i].toUpperCase() ) return false; } return true; }, function put(obj) { return this + obj.toJSON(); }, (function() { var map = {}; return function intern() { /** Convert a string to an internal canonical copy. **/ return map[this] || (map[this] = this.toString()); }; })(), function hashCode() { var hash = 0; if ( this.length == 0 ) return hash; for (i = 0; i < this.length; i++) { var code = this.charCodeAt(i); hash = ((hash << 5) - hash) + code; hash &= hash; } return hash; } ] }); MODEL({ extendsProto: 'Function', methods: [ /** * Replace Function.bind with a version * which is ~10X faster for the common case * where you're only binding 'this'. **/ (function() { var oldBind = Function.prototype.bind; var simpleBind = function(f, self) { return function() { return f.apply(self, arguments); }; /* var ret = function() { return f.apply(self, arguments); }; ret.toString = function bind() { return f.toString(); }; return ret; */ }; return function bind(arg) { return arguments.length == 1 ? simpleBind(this, arg) : oldBind.apply(this, argsToArray(arguments)); }; })(), function equals(o) { return this === o; }, function compareTo(o) { return this === o ? 0 : ( this.name.compareTo(o.name) || 1 ); }, function o(f2) { var f1 = this; return function() { return f1.call(this, f2.apply(this, argsToArray(arguments))); }; } ] }); MODEL({ extendsObject: 'Math', methods: [ function sign(n) { return n > 0 ? 1 : -1; } ] }); MODEL({ extendsProto: 'Date', methods: [ function toRelativeDateString(){ var seconds = Math.floor((Date.now() - this.getTime())/1000); if ( seconds < 60 ) return 'moments ago'; var minutes = Math.floor((seconds)/60); if ( minutes == 1 ) return '1 minute ago'; if ( minutes < 60 ) return minutes + ' minutes ago'; var hours = Math.floor(minutes/60); if ( hours == 1 ) return '1 hour ago'; if ( hours < 24 ) return hours + ' hours ago'; var days = Math.floor(hours / 24); if ( days == 1 ) return '1 day ago'; if ( days < 7 ) return days + ' days ago'; if ( days < 365 ) { var year = 1900+this.getYear(); var noyear = this.toDateString().replace(' ' + year, ''); return noyear.substring(4); } return this.toDateString().substring(4); }, function equals(o) { if ( ! o ) return false; if ( ! o.getTime ) return false; return this.getTime() === o.getTime(); }, function compareTo(o){ if ( o === this ) return 0; if ( ! o ) return 1; var d = this.getTime() - o.getTime(); return d == 0 ? 0 : d > 0 ? 1 : -1; }, function toMQL() { return this.getFullYear() + '/' + (this.getMonth() + 1) + '/' + this.getDate(); }, function toBQL() { var str = this.toISOString(); // eg. 2014-12-04T16:37:33.420Z return str.substring(0, str.indexOf('.')); // eg. 2014-12-04T16:37:33 } ] }); MODEL({ extendsProto: 'Number', methods: [ function compareTo(o) { return ( o == this ) ? 0 : this < o ? -1 : 1; }, ] }); MODEL({ extendsProto: 'Boolean', methods: [ function compareTo(o) { return (this.valueOf() ? 1 : 0) - (o ? 1 : 0); } ] }); MODEL({ extendsProto: 'RegExp', methods: [ function quote(str) { return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } ] }); console.log.json = function() { var args = []; for ( var i = 0 ; i < arguments.length ; i++ ) { var arg = arguments[i]; args.push(arg && arg.toJSON ? arg.toJSON() : arg); } console.log.apply(console, args); }; console.log.str = function() { var args = []; for ( var i = 0 ; i < arguments.length ; i++ ) { var arg = arguments[i]; args.push(arg && arg.toString ? arg.toString() : arg); } console.log.apply(console, args); }; // Promote 'console.log' into a Sink console.log.put = console.log.bind(console); console.log.remove = console.log.bind(console, 'remove: '); console.log.error = console.log.bind(console, 'error: '); console.log.json.put = console.log.json.bind(console); console.log.json.reduceI = console.log.json.bind(console, 'reduceI: '); console.log.json.remove = console.log.json.bind(console, 'remove: '); console.log.json.error = console.log.json.bind(console, 'error: '); console.log.str.put = console.log.str.bind(console); console.log.str.remove = console.log.str.bind(console, 'remove: '); console.log.str.error = console.log.str.bind(console, 'error: '); document.put = function(obj) { if ( obj.write ) { obj.write(this); } else { this.write(obj.toString()); } }; // Promote webkit apis; fallback on Node.js alternatives // TODO(kgr): this should be somewhere web specific window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.setImmediate; if ( window.Blob ) { Blob.prototype.slice = Blob.prototype.slice || Blob.prototype.webkitSlice; } if ( window.XMLHttpRequest ) { /** * Add an afunc send to XMLHttpRequest */ XMLHttpRequest.prototype.asend = function(ret, opt_data) { var xhr = this; xhr.onerror = function() { console.log('XHR Error: ', arguments); }; xhr.onloadend = function() { ret(xhr.response, xhr); }; xhr.send(opt_data); }; } String.fromCharCode = (function() { var oldLookup = String.fromCharCode; var lookupTable = []; return function(a) { if ( arguments.length == 1 ) return lookupTable[a] || (lookupTable[a] = oldLookup(a)); var result = ''; for ( var i = 0 ; i < arguments.length ; i++ ) result += lookupTable[arguments[i]] || (lookupTable[arguments[i]] = oldLookup(arguments[i])); return result; }; })(); var MementoProto = {}; Object.defineProperty(MementoProto, 'equals', { enumerable: false, configurable: true, value: function(o) { var keys = Object.keys(this); var otherKeys = Object.keys(o); if ( keys.length != otherKeys.length ) { return false; } for ( var i = 0 ; i < keys.length ; i++ ) { if ( ! equals(this[keys[i]], o[keys[i]]) ) return false; } return true; } }); /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ // WeakMap Polyfill, doesn't implement the full interface, just the parts // that FOAM uses. // TODO: Use defineProperty to make hidden property if ( ! window.WeakMap ) { function WeakMap() { var id = '__WEAK_MAP__' + this.$UID; function del(key) { delete key[id]; } function get(key) { return key[id]; } function set(key, value) { key[id] = value; } function has(key) { return !!key[id]; } return { __proto__: this, "delete": del, get: get, set: set, has: has }; } } /** * @license * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ // TODO: time-travelling debugger, ala: // "Debugging Standard ML Without Reverse Engineering" MODEL({ extendsProto: 'Function', methods: [ function abind(self) { /** Adapt a synchronous method into a psedo-afunc. **/ return function(ret) { this.apply(self, arguments); ret(); }.bind(this); }, function ao(f2) { /** Async Compose (like Function.prototype.O, but for async functions **/ var f1 = this; return function(ret) { var args = argsToArray(arguments); args[0] = f1.bind(this, ret); f2.apply(this, args); } }, function aseq(f2) { return f2.ao(this); } ] }); MODEL({ // TODO(kgr): put in a package rather than global, maybe foam.async extendsObject: 'GLOBAL', methods: [ /** NOP afunc. **/ function anop(ret) { ret && ret(undefined); }, /** afunc log. **/ function alog() { var args = arguments; return function (ret) { console.log.apply(console, args); ret && ret.apply(this, [].slice.call(arguments, 1)); }; }, /** console.profile an afunc. **/ function aprofile(afunc) { return function(ret) { var a = argsToArray(arguments); console.profile('aprofile'); var ret2 = function () { console.profileEnd(); ret && ret(arguments); }; aapply_(afunc, ret2, a); }; }, /** Create an afunc which always returns the supplied constant value. **/ function aconstant(v) { return function(ret) { ret && ret(v); }; }, /** Execute the supplied afunc N times. **/ function arepeat(n, afunc) { if ( ! n ) return anop; return function(ret) { var a = argsToArray(arguments); a.splice(1, 0, 0, n); // insert (0, n) after 'ret' argument var next = atramp(function() { if ( a[1] == n-1 ) { a[0] = ret; afunc.apply(this, a); return; }; afunc.apply(this, a); a[1]++; }); a[0] = next; next.apply(this, a); }; }, /** Execute the supplied afunc on each element of an array. */ function aforEach(arr, afunc) { // TODO: implement }, /** Execute the supplied afunc until cond() returns false. */ function awhile(cond, afunc) { return function(ret) { var a = argsToArray(arguments); var g = function() { if ( ! cond() ) { ret.apply(undefined, arguments); return; } afunc.apply(this, a); }; a[0] = g; g.apply(this, a); }; }, /** Execute the supplied afunc if cond. */ function aif(cond, afunc, aelse) { return function(ret) { if ( typeof cond === 'function' ? cond() : cond ) { afunc.apply(this, arguments); } else { if ( aelse ) aelse.apply(this, arguments); else ret(); } }; }, /** Execute afunc if the acond returns true */ function aaif(acond, afunc, aelse) { return function(ret) { var args = argsToArray(arguments); args[0] = function(c) { args[0] = ret; if ( c ) afunc.apply(null, args); else if ( aelse ) aelse.apply(null, args); else ret(); }; acond.apply(null, args); } }, /** Time an afunc. **/ (function() { // Add a unique suffix to timer names in case multiple instances // of the same timing are active at once. var id = 1; var activeOps = {}; return function atime(str, afunc, opt_endCallback, opt_startCallback) { var name = str; return aseq( function(ret) { if ( activeOps[str] ) { name += '-' + id++; activeOps[str]++; } else { activeOps[str] = 1; } var start = performance.now(); if ( opt_startCallback ) opt_startCallback(name); if ( ! opt_endCallback ) console.time(name); ret.apply(null, [].slice.call(arguments, 1)); }, afunc, function(ret) { activeOps[str]--; if ( opt_endCallback ) { var end = performance.now(); opt_endCallback(name, end - start); } else { console.timeEnd(name); } ret && ret.apply(null, [].slice.call(arguments, 1)); } ); }; })(), /** Time an afunc and record its time as a metric. **/ function ametric() { return this.atime.apply(this, arguments); }, /** Sleep for the specified delay. **/ function asleep(ms) { return function(ret) { window.setTimeout(ret, ms); }; }, function ayield() { return function(ret) { window.setTimeout(ret, 0); }; }, /** Create a future value. **/ function afuture() { var set = false; var values = undefined; var waiters = []; return { set: function() { if ( set ) { console.log('ERROR: redundant set on future'); return; } values = arguments; set = true; for (var i = 0 ; i < waiters.length; i++) { waiters[i].apply(null, values); } waiters = undefined; return this; }, get: function(ret) { if ( set ) { ret.apply(null, values); return; } waiters.push(ret); } }; }, function aapply_(f, ret, args) { args.unshift(ret); f.apply(this, args); }, /** * A request queue that reduces each request against the pending requests. * Also limits the queue to a maximum size and operates in a LIFO manner. * TODO: This could probably be split into decorators and integrated with asynchronized. */ function arequestqueue(f, opt_lock, opt_max) { var lock = opt_lock || {}; if ( ! lock.q ) { lock.q = []; lock.active = null; } var onExit = function() { var next = lock.active = lock.q.pop(); if ( next ) { setTimeout(function() { f(onExit, next); }, 0); } }; var reduceDown = function(o, q) { for ( var i = q.length -1 ; i >= 0 ; i-- ) { var result = o.reduce(q[i]); if ( result ) { q.splice(i, 1); reduceDown(result, q); break; } } q.push(o); } return function(o) { if ( lock.active ) { // If the next request reduces into the active one, then forget about it. var first = o.reduce(lock.active); if ( first && first.equals(lock.active) ) return; } reduceDown(o, lock.q, lock.q.length - 1); if ( lock.q.length > opt_max ) lock.q.length = opt_max; if ( ! lock.active ) onExit(); }; }, /** * A Binary Semaphore which only allows the delegate function to be * executed by a single thread of execution at once. * Like Java's synchronized blocks. * @param opt_lock an empty map {} to be used as a lock * sharable across multiple asynchronized instances **/ function asynchronized(f, opt_lock) { var lock = opt_lock || {}; if ( ! lock.q ) { lock.q = []; lock.active = false; } // Decorate 'ret' to check for blocked continuations. function onExit(ret) { return function() { var next = lock.q.shift(); if ( next ) { setTimeout(next, 0); } else { lock.active = false; } ret(); }; } return function(ret) { // Semaphore is in use, so just queue f for execution when the current // continuation exits. if ( lock.active ) { lock.q.push(function() { f(onExit(ret)); }); return; } lock.active = true; f(onExit(ret)); }; }, /** * Execute an optional timeout function and abort the continuation * of the delegate function, if it doesn't finish in the specified * time. **/ // Could be generalized into an afirst() combinator which allows // for the execution of multiple streams but only the first to finish // gets to continue. function atimeout(delay, f, opt_timeoutF) { return function(ret) { var timedOut = false; var completed = false; setTimeout(function() { if ( completed ) return; timedOut = true; console.log('timeout'); opt_timeoutF && opt_timeoutF(); }, delay); f(aseq( function(ret) { if ( ! timedOut ) completed = true; if ( completed ) ret(); }, ret)); }; }, /** * Memoize an async function. **/ function amemo(f, opt_ttl) { var memoized = false; var values; var waiters; var age = 0; var pending = false return function(ret) { if ( memoized ) { ret.apply(null, values); if ( opt_ttl != undefined && ! pending && Date.now() > age + opt_ttl ) { pending = true; f(function() { values = arguments; age = Date.now(); pending = false; }) } return; } var first = ! waiters; if ( first ) waiters = []; waiters.push(ret); if ( first ) { f(function() { values = arguments; age = Date.now(); for (var i = 0 ; i < waiters.length; i++) { waiters[i] && waiters[i].apply(null, values); } if ( opt_ttl == undefined ) f = undefined; memoized = true; waiters = undefined; }); } }; }, /** * Decorates an afunc to merge all calls to one active execution of the * delegate. * Similar to asynchronized, but doesn't queue up a number of calls * to the delegate. */ function amerged(f) { var waiters; return function(ret) { var first = ! waiters; if ( first ) { waiters = []; var args = argsToArray(arguments); } waiters.push(ret); if ( first ) { args[0] = function() { var calls = waiters; waiters = undefined; for (var i = 0 ; i < calls.length; i++) { calls[i] && calls[i].apply(null, arguments); } } f.apply(null, args); } }; }, /** * Decorates an afunc to merge calls. * NB: This does not return an afunc itself! * * Immediately fires on the first call. If more calls come in while the first is * active, they are merged into one subsequent call with the latest arguments. * Once the first call is complete, the afunc will fire again if any further * calls have come in. If there are no more, then it will rest. * * The key difference from amerged is that it makes one call to the afunc but * calls its own ret once for *each* call it has received. This calls only once. */ function mergeAsync(f) { var active = false; var args; return function() { if ( active ) { args = argsToArray(arguments); return; } active = true; // Otherwise, call f with the arguments I've been given, plus the ret // handler. var ret = function() { // If args is set, we have received further calls. if ( args ) { args.unshift(ret); f.apply(null, args); args = undefined; } else { active = false; } }; var a = argsToArray(arguments); a.unshift(ret); f.apply(null, a); }; }, /** Compose a variable number of async functions. **/ function ao(/* ... afuncs */) { var ret = arguments[arguments.length-1]; for ( var i = 0 ; i < arguments.length-1 ; i++ ) { ret = arguments[i].ao(ret); } return ret; }, /** Compose a variable number of async functions. **/ function aseq(/* ... afuncs */) { var f = arguments[arguments.length-1]; for ( var i = arguments.length-2 ; i >= 0 ; i-- ) { f = arguments[i].aseq(f); } return f; }, /** * Create a function which executes several afunc's in parallel and passes * their joined return values to an optional afunc. * * Usage: apar(f1,f2,f3)(opt_afunc, opt_args) * @param opt_afunc called with joined results after all afuncs finish * @param opt_args passed to all afuncs **/ function apar(/* ... afuncs */) { var aargs = []; var count = 0; var fs = arguments; return function(ret /* opt_args */) { if ( fs.length == 0 ) { ret && ret(); return; } var opt_args = Array.prototype.splice.call(arguments, 1); var ajoin = function (i) { aargs[i] = Array.prototype.splice.call(arguments, 1); if ( ++count == fs.length ) { var a = []; for ( var j = 0 ; j < fs.length ; j++ ) for ( var k = 0 ; k < aargs[j].length ; k++ ) a.push(aargs[j][k]); ret && ret.apply(null, a); } }; for ( var i = 0 ; i < fs.length ; i++ ) fs[i].apply(null, [ajoin.bind(null, i)].concat(opt_args)); }; }, /** Convert the supplied afunc into a trampolined-afunc. **/ (function() { var active = false; var jobs = []; return function atramp(afunc) { return function() { jobs.push([afunc, arguments]); if ( ! active ) { console.assert( jobs.length <= 1, 'atramp with multiple jobs'); active = true; var job; // Take responsibility for bouncing while ( (job = jobs.pop()) != null ) { job[0].apply(this, job[1]); } active = false; } }; }; })(), /** Execute the supplied afunc concurrently n times. **/ function arepeatpar(n, afunc) { return function(ret /* opt_args */) { if ( n === 0 ) { ret && ret(); return; } var aargs = []; var count = 0; var opt_args = Array.prototype.splice.call(arguments, 1); var ajoin = function (i) { // aargs[i] = Array.prototype.splice.call(arguments, 1); if ( ++count == n ) { var a = []; /* for ( var j = 0 ; j < n ; j++ ) for ( var k = 0 ; k < aargs[j].length ; k++ ) a.push(aargs[j][k]); */ ret && ret.apply(null, a); } }; for ( var i = 0 ; i < n ; i++ ) { afunc.apply(null, [ajoin.bind(null, i)].concat([i, n]).concat(opt_args)); } }; }, function axhr(url, opt_op, opt_params) { var op = opt_op || "GET"; var params = opt_params || []; return function(ret) { var xhr = new XMLHttpRequest(); xhr.open(op, url); xhr.asend(function(json) { ret(JSON.parse(json)); }, params && params.join('&')); }; }, function futurefn(future) { return function() { var args = arguments; future.get(function(f) { f.apply(undefined, args); }); }; }, function adelay(afunc, delay) { var queue = []; var timeout; function pump() { if ( timeout ) return; if ( ! queue.length ) return; var top = queue.shift(); var f = top[0]; var args = top[1]; var ret = args[0]; args[0] = function() { ret.apply(null, arguments); pump(); }; timeout = setTimeout(function() { timeout = 0; f.apply(null, args); }, delay) } return function() { var args = arguments; queue.push([ afunc, args ]); pump(); }; }, function adebugger(fn) { return function(ret) { debugger fn.apply(null, arguments); }; } ] }); // TODO(kgr): Move somewhere better. var __JSONP_CALLBACKS__ = {}; var wrapJsonpCallback = (function() { var nextID = 0; return function(ret, opt_nonce) { var id = 'c' + (nextID++); if ( opt_nonce ) id += Math.floor(Math.random() * 0xffffff).toString(16); var cb = __JSONP_CALLBACKS__[id] = function(data) { delete __JSONP_CALLBACKS__[id]; // console.log('JSONP Callback', id, data); ret && ret.call(this, data); }; cb.id = id; return cb; }; })(); // Note: this doesn't work for packaged-apps var ajsonp = function(url, params) { return function(ret) { var cb = wrapJsonpCallback(ret); var script = document.createElement('script'); script.src = url + '?callback=__JSONP_CALLBACKS__.' + cb.id + (params ? '&' + params.join('&') : ''); script.onload = function() { document.body.removeChild(this); }; script.onerror = function() { cb(null); document.body.removeChild(this); }; document.body.appendChild(script); }; }; /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /* var ErrorReportingPS = { create: function(delegate, opt_pos) { console.log('ERPS:',delegate.head); return { __proto__: this, pos: opt_pos || 0, delegate: delegate }; }, get head() { console.log('head:',this.pos, this.delegate.head); return this.delegate.head; }, get tail() { return this.tail_ || (this.tail_ = this.create(this.delegate.tail, this.pos+1)); }, get value() { return this.delegate.value; }, setValue: function(value) { console.log('setValue:',value); // return ErrorReportingPS.create(this.delegate.setValue(value)); this.delegate = this.delegate.setValue(value); return this; } }; */ /** String PStream **/ var StringPS = { create: function(str) { var o = Object.create(this); o.pos = 0; o.str_ = [str]; o.tail_ = []; return o; }, set str(str) { this.str_[0] = str; }, get head() { return this.pos >= this.str_[0].length ? null : this.str_[0].charAt(this.pos); }, // TODO(kgr): next line is slow because it can't bet JITed, fix. get value() { return this.hasOwnProperty('value_') ? this.value_ : this.str_[0].charAt(this.pos-1); }, get tail() { if ( ! this.tail_[0] ) { var tail = Object.create(this.__proto__); tail.str_ = this.str_; tail.pos = this.pos+1; tail.tail_ = []; this.tail_[0] = tail; } return this.tail_[0]; }, setValue: function(value) { var ret = Object.create(this.__proto__); ret.str_ = this.str_; ret.pos = this.pos; ret.tail_ = this.tail_; ret.value_ = value; return ret; }, toString: function() { return this.str_[0].substring(this.pos); } }; function prep(arg) { if ( typeof arg === 'string' ) return literal(arg); return arg; } function prepArgs(args) { for ( var i = 0 ; i < args.length ; i++ ) { args[i] = prep(args[i]); } return args; } function range(c1, c2) { var f = function(ps) { if ( ! ps.head ) return undefined; if ( ps.head < c1 || ps.head > c2 ) return undefined; return ps.tail.setValue(ps.head); }; f.toString = function() { return 'range(' + c1 + ', ' + c2 + ')'; }; return f; } function literal(str, opt_value) { var f = function(ps) { for ( var i = 0 ; i < str.length ; i++, ps = ps.tail ) { if ( str.charAt(i) !== ps.head ) return undefined; } return ps.setValue(opt_value || str); }; f.toString = function() { return '"' + str + '"'; }; return f; } /** * Case-insensitive String literal. * Doesn't work for Unicode characters. **/ function literal_ic(str, opt_value) { str = str.toLowerCase(); var f = function(ps) { for ( var i = 0 ; i < str.length ; i++, ps = ps.tail ) { if ( ! ps.head || str.charAt(i) !== ps.head.toLowerCase() ) return undefined; } return ps.setValue(opt_value || str); }; f.toString = function() { return '"' + str + '"'; }; return f; } function anyChar(ps) { return ps.head ? ps.tail/*.setValue(ps.head)*/ : undefined; } function notChar(c) { return function(ps) { return ps.head && ps.head !== c ? ps.tail.setValue(ps.head) : undefined; }; } function notChars(s) { return function(ps) { return ps.head && s.indexOf(ps.head) == -1 ? ps.tail.setValue(ps.head) : undefined; }; } function not(p, opt_else) { p = prep(p); opt_else = prep(opt_else); var f = function(ps) { return this.parse(p,ps) ? undefined : opt_else ? this.parse(opt_else, ps) : ps; }; f.toString = function() { return 'not(' + p + ')'; }; return f; } function optional(p) { p = prep(p); var f = function(ps) { return this.parse(p,ps) || ps.setValue(undefined); }; f.toString = function() { return 'optional(' + p + ')'; }; return f; } function copyInput(p) { p = prep(p); var f = function(ps) { var res = this.parse(p, ps); return res ? res.setValue(ps.str_.toString().substring(ps.pos, res.pos)) : res; }; f.toString = function() { return 'copyInput(' + p + ')'; }; return f; } /** Parses if the delegate parser parses, but doesn't advance the pstream. **/ function lookahead(p) { p = prep(p); var f = function(ps) { return this.parse(p,ps) && ps; }; f.toString = function() { return 'lookahead(' + p + ')'; }; return f; } function repeat(p, opt_delim, opt_min, opt_max) { p = prep(p); opt_delim = prep(opt_delim); var f = function(ps) { var ret = []; for ( var i = 0 ; ! opt_max || i < opt_max ; i++ ) { var res; if ( opt_delim && ret.length != 0 ) { if ( ! ( res = this.parse(opt_delim, ps) ) ) break; ps = res; } if ( ! ( res = this.parse(p,ps) ) ) break; ret.push(res.value); ps = res; } if ( opt_min && ret.length < opt_min ) return undefined; return ps.setValue(ret); }; f.toString = function() { return 'repeat(' + p + ', ' + opt_delim + ', ' + opt_min + ', ' + opt_max + ')'; }; return f; } function plus(p) { return repeat(p, undefined, 1); } function noskip(p) { return function(ps) { this.skip_ = false; ps = this.parse(p, ps); this.skip_ = true; return ps; }; } /** A simple repeat which doesn't build an array of parsed values. **/ function repeat0(p) { p = prep(p); return function(ps) { var res; while ( res = this.parse(p, ps) ) ps = res; return ps.setValue(''); }; } function seq(/* vargs */) { var args = prepArgs(arguments); var f = function(ps) { var ret = []; for ( var i = 0 ; i < args.length ; i++ ) { if ( ! ( ps = this.parse(args[i], ps) ) ) return undefined; ret.push(ps.value); } return ps.setValue(ret); }; f.toString = function() { return 'seq(' + argsToArray(args).join(',') + ')'; }; return f; } /** * A Sequence which only returns one of its arguments. * Ex. seq1(1, '"', sym('string'), '"'), **/ function seq1(n /*, vargs */) { var args = prepArgs(argsToArray(arguments).slice(1)); var f = function(ps) { var ret; for ( var i = 0 ; i < args.length ; i++ ) { if ( ! ( ps = this.parse(args[i], ps) ) ) return undefined; if ( i == n ) ret = ps.value; } return ps.setValue(ret); }; f.toString = function() { return 'seq1(' + n + ', ' + argsToArray(args).join(',') + ')'; }; return f; } var parserVersion_ = 1; function invalidateParsers() { parserVersion_++; } function simpleAlt(/* vargs */) { //function alt(/* vargs */) { var args = prepArgs(arguments); if ( args.length == 1 ) return args[0]; var f = function(ps) { for ( var i = 0 ; i < args.length ; i++ ) { var res = this.parse(args[i], ps); if ( res ) return res; } return undefined; }; f.toString = function() { return 'alt(' + argsToArray(args).join(' | ') + ')'; }; return f; } var TrapPStream = { create: function(ps) { return { __proto__: this, head: ps.head, value: ps.value, goodChar: false }; }, getValue: function() { return this.value; }, setValue: function(v) { this.value = v; return this; }, get tail() { this.goodChar = true; return { value: this.value, getValue: function() { return this.value; }, setValue: function(v) { this.value = v; } }; } }; function alt(/* vargs */) { var SIMPLE_ALT = simpleAlt.apply(null, arguments); var args = prepArgs(arguments); var map = {}; var parserVersion = parserVersion_; function nullParser() { return undefined; } function testParser(p, ps) { var trapPS = TrapPStream.create(ps); this.parse(p, trapPS); // console.log('*** TestParser:',p,c,goodChar); return trapPS.goodChar; } function getParserForChar(ps) { var c = ps.head; var p = map[c]; if ( ! p ) { var alts = []; for ( var i = 0 ; i < args.length ; i++ ) { var parser = args[i]; if ( testParser.call(this, parser, ps) ) alts.push(parser); } p = alts.length == 0 ? nullParser : alts.length == 1 ? alts[0] : simpleAlt.apply(null, alts); map[c] = p; } return p; } return function(ps) { if ( parserVersion !== parserVersion_ ) { map = {}; parserVersion = parserVersion_; } var r1 = this.parse(getParserForChar.call(this, ps), ps); // If alt and simpleAlt don't return same value then uncomment this // section to find out where the problem is occuring. /* var r2 = this.parse(SIMPLE_ALT, ps); if ( ! r1 !== ! r2 ) debugger; if ( r1 && ( r1.pos !== r2.pos ) ) debugger; */ return r1; }; } /** Takes a parser which returns an array, and converts its result to a String. **/ function str(p) { p = prep(p); var f = function(ps) { var ps = this.parse(p, ps); return ps ? ps.setValue(ps.value.join('')) : undefined ; }; f.toString = function() { return 'str(' + p + ')'; }; return f; } /** Ex. attr: pick([0, 2], seq(sym('label'), '=', sym('value'))) **/ function pick(as, p) { p = prep(p); var f = function(ps) { var ps = this.parse(p, ps); if ( ! ps ) return undefined; var ret = []; for ( var i = 0 ; i < as.length ; i++ ) ret.push(ps.value[as[i]]); return ps.setValue(ret); }; f.toString = function() { return 'pick(' + as + ', ' + p + ')'; }; return f; } function parsedebug(p) { return function(ps) { debugger; var old = DEBUG_PARSE; DEBUG_PARSE = true; var ret = this.parse(p, ps); DEBUG_PARSE = old; return ret; }; } // alt = simpleAlt; function sym(name) { var f = function(ps) { var p = this[name]; if ( ! p ) console.log('PARSE ERROR: Unknown Symbol <' + name + '>'); return this.parse(p, ps); }; f.toString = function() { return '<' + name + '>'; }; return f; } // This isn't any faster because V8 does the same thing already. // function sym(name) { var p; return function(ps) { return (p || ( p = this[name])).call(this, ps); }; } // function sym(name) { return function(ps) { var ret = this[name](ps); console.log('<' + name + '> -> ', !! ret); return ret; }; } var DEBUG_PARSE = false; var grammar = { parseString: function(str) { var ps = this.stringPS; ps.str = str; var res = this.parse(this.START, ps); return res && res.value; }, parse: function(parser, pstream) { // if ( DEBUG_PARSE ) console.log('parser: ', parser, 'stream: ',pstream); if ( DEBUG_PARSE && pstream.str_ ) { console.log(new Array(pstream.pos).join('.'), pstream.head); console.log(pstream.pos + '> ' + pstream.str_[0].substring(0, pstream.pos) + '(' + pstream.head + ')'); } var ret = parser.call(this, pstream); if ( DEBUG_PARSE ) { console.log(parser + ' ==> ' + (!!ret) + ' ' + (ret && ret.value)); } return ret; }, /** Export a symbol for use in another grammar or stand-alone. **/ 'export': function(str) { return this[str].bind(this); }, addAction: function(sym, action) { var p = this[sym]; this[sym] = function(ps) { var val = ps.value; var ps2 = this.parse(p, ps); return ps2 && ps2.setValue(action.call(this, ps2.value, val)); }; this[sym].toString = function() { return '<<' + sym + '>>'; }; }, addActions: function(map) { for ( var key in map ) this.addAction(key, map[key]); return this; } }; // TODO(kgr): move this somewhere better function defineTTLProperty(obj, name, ttl, f) { obj.__defineGetter__(name, function() { var accessed; var value = undefined; this.__defineGetter__(name, function() { function scheduleTimer() { setTimeout(function() { if ( accessed ) { scheduleTimer(); } else { value = undefined; } accessed = false; }, ttl); } if ( ! value ) { accessed = false; value = f(); scheduleTimer(); } else { accessed = true; } return value; }); return this[name]; }); } defineTTLProperty(grammar, 'stringPS', 30000, function() { return StringPS.create(''); }); var SkipGrammar = { create: function(gramr, skipp) { return { __proto__: gramr, skip_: true, parse: function(parser, pstream) { if (this.skip_) pstream = this.skip.call(grammar, pstream) || pstream; return this.__proto__.parse.call(this, parser, pstream); }, skip: skipp }; } }; // TODO: move this out of Core /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ // todo: add enabled/disabled support // todo: bind // todo: generateTopic() // todo: cleanup empty topics after subscriptions removed /** Publish and Subscribe Event Notification Service. **/ // ??? Whould 'Observable' be a better name? // TODO(kgr): Model or just make part of FObject? var __ROOT__ = {}; MODEL({ name: 'EventService', extendsModel: '__ROOT__', constants: { /** If listener thows this exception, it will be removed. **/ UNSUBSCRIBE_EXCEPTION: 'unsubscribe', /** Used as topic suffix to specify broadcast to all sub-topics. **/ WILDCARD: '*' }, methods: { /** Create a "one-time" listener which unsubscribes itself after its first invocation. **/ oneTime: function(listener) { return function() { listener.apply(this, argsToArray(arguments)); throw EventService.UNSUBSCRIBE_EXCEPTION; }; }, /** Log all listener invocations to console. **/ consoleLog: function(listener) { return function() { var args = argsToArray(arguments); console.log(args); listener.apply(this, args); }; }, /** * Merge all notifications occuring in the specified time window into a single notification. * Only the last notification is delivered. * * @param opt_delay time in milliseconds of time-window, defaults to 16ms, which is * the smallest delay that humans aren't able to perceive. **/ merged: function(listener, opt_delay, opt_X) { var setTimeoutX = ( opt_X && opt_X.setTimeout ) || setTimeout; var delay = opt_delay || 16; return function() { var triggered = false; var unsubscribed = false; var lastArgs = null; var f = function() { lastArgs = arguments; if ( unsubscribed ) throw EventService.UNSUBSCRIBE_EXCEPTION; if ( ! triggered ) { triggered = true; try { setTimeoutX( function() { triggered = false; var args = argsToArray(lastArgs); lastArgs = null; try { listener.apply(this, args); } catch (x) { if ( x === EventService.UNSUBSCRIBE_EXCEPTION ) unsubscribed = true; } }, delay); } catch(e) { // TODO: Clean this up when we move EventService into the context. throw EventService.UNSUBSCRIBE_EXCEPTION; } } }; if ( DEBUG ) f.toString = function() { return 'MERGED(' + delay + ', ' + listener.$UID + ', ' + listener + ')'; }; return f; }(); }, /** * Merge all notifications occuring until the next animation frame. * Only the last notification is delivered. **/ // TODO: execute immediately from within a requestAnimationFrame framed: function(listener, opt_X) { opt_X = opt_X || this.X; var requestAnimationFrameX = ( opt_X && opt_X.requestAnimationFrame ) || requestAnimationFrame; return function() { var triggered = false; var unsubscribed = false; var lastArgs = null; var f = function() { lastArgs = arguments; if ( unsubscribed ) throw EventService.UNSUBSCRIBE_EXCEPTION; if ( ! triggered ) { triggered = true; requestAnimationFrameX( function() { triggered = false; var args = argsToArray(lastArgs); lastArgs = null; try { listener.apply(this, args); } catch (x) { if ( x === EventService.UNSUBSCRIBE_EXCEPTION ) unsubscribed = true; } }); } }; if ( DEBUG ) f.toString = function() { return 'ANIMATE(' + listener.$UID + ', ' + listener + ')'; }; return f; }(); }, /** Decroate a listener so that the event is delivered asynchronously. **/ async: function(listener, opt_X) { return this.delay(0, listener, opt_X); }, delay: function(delay, listener, opt_X) { opt_X = opt_X || this.X; return function() { var args = argsToArray(arguments); // Is there a better way of doing this? (opt_X && opt_X.setTimeout ? opt_X.setTimeout : setTimeout)( function() { listener.apply(this, args); }, delay ); }; }, hasListeners: function (opt_topic) { if ( ! opt_topic ) return !! this.subs_; console.log('TODO: haslisteners'); // TODO: return true; }, /** * Publish a notification to the specified topic. * * @return number of subscriptions notified **/ publish: function (topic) { return this.subs_ ? this.pub_( this.subs_, 0, topic, this.appendArguments([this, topic], arguments, 1)) : 0; }, /** Publish asynchronously. **/ publishAsync: function (topic) { var args = argsToArray(arguments); var me = this; setTimeout( function() { me.publish.apply(me, args); }, 0); }, /** * Publishes a message to this object and all of its children. * Objects/Protos which have children should override the * standard definition, which is the same as just calling publish(). **/ deepPublish: function(topic) { return this.publish.apply(this, arguments); }, /** * Publish a message supplied by a factory function. * * This is useful if the message is expensive to generate and you * don't want to waste the effort if there are no listeners. * * arg fn: function which returns array **/ lazyPublish: function (topic, fn) { if ( this.hasListeners(topic) ) return this.publish.apply(this, fn()); return 0; }, /** Subscribe to notifications for the specified topic. **/ subscribe: function (topic, listener) { if ( ! this.subs_ ) this.subs_ = {}; //console.log("Sub: ",this, listener); this.sub_(this.subs_, 0, topic, listener); }, /** Unsubscribe a listener from the specified topic. **/ unsubscribe: function (topic, listener) { if ( ! this.subs_ ) return; this.unsub_(this.subs_, 0, topic, listener); }, /** Unsubscribe all listeners from this service. **/ unsubscribeAll: function () { this.sub_ = {}; }, /////////////////////////////////////////////////////// // Internal ///////////////////////////////////////////////////// pub_: function(map, topicIndex, topic, msg) { var count = 0; // There are no subscribers, so nothing to do if ( map == null ) return 0; if ( topicIndex < topic.length ) { var t = topic[topicIndex]; // wildcard publish, so notify all sub-topics, instead of just one if ( t == this.WILDCARD ) return this.notifyListeners_(topic, map, msg); if ( t ) count += this.pub_(map[t], topicIndex+1, topic, msg); } count += this.notifyListeners_(topic, map[null], msg); return count; }, sub_: function(map, topicIndex, topic, listener) { if ( topicIndex == topic.length ) { if ( ! map[null] ) map[null] = []; map[null].push(listener); } else { var key = topic[topicIndex]; if ( ! map[key] ) map[key] = {}; this.sub_(map[key], topicIndex+1, topic, listener); } }, unsub_: function(map, topicIndex, topic, listener) { if ( topicIndex == topic.length ) { if ( ! map[null] ) return true; if ( ! map[null].deleteI(listener) ) { console.warn('phantom unsubscribe, size: ', map[null].length); } else { // console.log('remove', topic); } if ( ! map[null].length ) delete map[null]; } else { var key = topic[topicIndex]; if ( ! map[key] ) return false; if ( this.unsub_(map[key], topicIndex+1, topic, listener) ) delete map[key]; } return Object.keys(map).length == 0; }, /** @return true if the message was delivered without error. **/ notifyListener_: function(topic, listener, msg) { try { listener.apply(null, msg); } catch ( err ) { if ( err !== this.UNSUBSCRIBE_EXCEPTION ) { console.error('Error delivering event (removing listener): ', topic.join('.'), err); } else { // console.warn('Unsubscribing listener: ', topic.join('.')); } return false; } return true; }, /** @return number of listeners notified **/ notifyListeners_: function(topic, listeners, msg) { if ( listeners == null ) return 0; if ( Array.isArray(listeners) ) { for ( var i = 0 ; i < listeners.length ; i++ ) { var listener = listeners[i]; if ( ! this.notifyListener_(topic, listener, msg) ) { listeners.splice(i,1); i--; } } return listeners.length; } var count = 0; for ( var key in listeners ) { count += this.notifyListeners_(topic, listeners[key], msg); } return count; }, // convenience method to turn 'arguments' into a real array appendArguments: function (a, args, start) { for ( var i = start ; i < args.length ; i++ ) a.push(args[i]); return a; } } }); /** Extend EventService with support for dealing with property-change notification. **/ MODEL({ name: 'PropertyChangeSupport', extendsModel: 'EventService', constants: { /** Root for property topics. **/ PROPERTY_TOPIC: 'property' }, methods: { /** Create a topic for the specified property name. **/ propertyTopic: memoize1(function (property) { return [ this.PROPERTY_TOPIC, property ]; }), /** Indicate that a specific property has changed. **/ propertyChange: function (property, oldValue, newValue) { // don't bother firing event if there are no listeners if ( ! this.subs_ ) return; // don't fire event if value didn't change if ( property != null && ( oldValue === newValue || (/*NaN check*/(oldValue !== oldValue) && (newValue !== newValue)) ) ) return; this.publish(this.propertyTopic(property), oldValue, newValue); }, propertyChange_: function (propertyTopic, oldValue, newValue) { // don't bother firing event if there are no listeners if ( ! this.subs_ ) return; // don't fire event if value didn't change if ( oldValue === newValue || (/*NaN check*/(oldValue !== oldValue) && (newValue !== newValue)) ) return; this.publish(propertyTopic, oldValue, newValue); }, /** Indicates that one or more unspecified properties have changed. **/ globalChange: function () { this.publish(this.propertyTopic(this.WILDCARD), null, null); }, addListener: function(listener) { console.assert(listener, 'Listener cannot be null.'); // this.addPropertyListener([ this.PROPERTY_TOPIC ], listener); this.addPropertyListener(null, listener); }, removeListener: function(listener) { this.removePropertyListener(null, listener); }, /** @arg property the name of the property to listen to or 'null' to listen to all properties. **/ addPropertyListener: function(property, listener) { this.subscribe(this.propertyTopic(property), listener); }, removePropertyListener: function(property, listener) { this.unsubscribe(this.propertyTopic(property), listener); }, /** Create a Value for the specified property. **/ propertyValue: function(prop) { if ( ! prop ) throw 'Property Name required for propertyValue().'; var props = this.props_ || ( this.props_ = {} ); return Object.hasOwnProperty.call(props, prop) ? props[prop] : ( props[prop] = PropertyValue.create(this, prop) ); } } }); var FunctionStack = { create: function() { var stack = [false]; return { stack: stack, push: function(f) { stack.unshift(f); }, pop: function() { stack.shift(); }, }; } }; var PropertyValue = { create: function(obj, prop) { var o = Object.create(this); o.$UID = obj.$UID + '.' + prop; o.obj = obj; o.prop = prop; return o; }, get: function() { return this.obj[this.prop]; }, set: function(val) { this.obj[this.prop] = val; }, // asDAO: function() { // console.warn('ProperytValue.asDAO() deprecated. Use property$Proxy instead.'); // if ( ! this.proxy ) { // this.proxy = this.X.lookup('foam.dao.ProxyDAO').create({delegate: this.get()}); // this.addListener(function() { proxy.delegate = this.get(); }.bind(this)); // } // return this.proxy; // }, get value() { return this.get(); }, set value(val) { this.set(val); }, addListener: function(listener) { this.obj.addPropertyListener(this.prop, listener); }, removeListener: function(listener) { this.obj.removePropertyListener(this.prop, listener); }, toString: function () { return 'PropertyValue(' + this.prop + ')'; } }; /** Static support methods for working with Events. **/ var Events = { /** Collection of all 'following' listeners. **/ listeners_: new WeakMap(), recordListener: function(src, dst, listener, opt_dontCallListener) { var srcMap = this.listeners_.get(src); if ( ! srcMap ) { srcMap = new WeakMap(); this.listeners_.set(src, srcMap); } console.assert( ! srcMap.get(dst), 'recordListener: duplicate follow'); srcMap.set(dst, listener); src.addListener(listener); if ( ! opt_dontCallListener ) listener(); }, identity: function (x) { return x; }, /** Have the dstValue listen to changes in the srcValue and update its value to be the same. **/ follow: function (srcValue, dstValue) { if ( ! srcValue || ! dstValue ) return; this.recordListener(srcValue, dstValue, function () { var sv = srcValue.get(); var dv = dstValue.get(); if ( ! equals(sv, dv) ) dstValue.set(sv); }); }, /** Have the dstValue stop listening for changes to the srcValue. **/ unfollow: function (src, dst) { if ( ! src || ! dst ) return; var srcMap = this.listeners_.get(src); if ( ! srcMap ) return; var listener = srcMap.get(dst); if ( listener ) { srcMap.delete(dst); src.removeListener(listener); } }, /** * Maps values from one model to another. * @param f maps values from srcValue to dstValue */ map: function (srcValue, dstValue, f) { if ( ! srcValue || ! dstValue ) return; this.recordListener(srcValue, dstValue, function () { var s = f(srcValue.get()); var d = dstValue.get(); if ( ! equals(s, d) ) dstValue.set(s); }); }, /** * Link the values of two models by having them follow each other. * Initial value is copied from srcValue to dstValue. **/ link: function (srcValue, dstValue) { this.follow(srcValue, dstValue); this.follow(dstValue, srcValue); }, /** * Relate the values of two models. * @param f maps value1 to model2 * @param fprime maps model2 to value1 * @param removeFeedback disables feedback */ relate: function (srcValue, dstValue, f, fprime, removeFeedback) { if ( ! srcValue || ! dstValue ) return; var feedback = false; var l = function(sv, dv, f) { return function () { if ( removeFeedback && feedback ) return; var s = f(sv.get()); var d = dv.get(); if ( ! equals(s, d) ) { feedback = true; dv.set(s); feedback = false; } }}; var l1 = l(srcValue, dstValue, f); var l2 = l(dstValue, srcValue, fprime); this.recordListener(srcValue, dstValue, l1, true); this.recordListener(dstValue, srcValue, l2, true); l1(); }, /** Unlink the values of two models by having them no longer follow each other. **/ unlink: function (value1, value2) { this.unfollow(value1, value2); this.unfollow(value2, value1); }, ////////////////////////////////////////////////// // FRP Support ////////////////////////////////////////////////// /** * Trap the dependencies of 'fn' and re-invoke whenever * their values change. The return value of 'fn' is * passed to 'opt_fn'. * @param opt_fn also invoked when dependencies change, * but its own dependencies are not tracked. * @returns a cleanup object. call ret.destroy(); to * destroy the dynamic function and listeners. */ dynamic: function(fn, opt_fn, opt_X) { var fn2 = opt_fn ? function() { opt_fn(fn()); } : fn; var listener = EventService.framed(fn2, opt_X); var propertyValues = []; fn(); // Call once before capture to pre-latch lazy values Events.onGet.push(function(obj, name, value) { // Uncomment next line to debug. // obj.propertyValue(name).addListener(function() { console.log('name: ', name, ' listener: ', listener); }); obj.propertyValue(name).addListener(listener); propertyValues.push(obj.propertyValue(name)); }); var ret = fn(); Events.onGet.pop(); opt_fn && opt_fn(ret); return { destroy: function() { // TODO(jacksonic): just return the function? propertyValues.forEach(function(p) { p.removeListener(listener); }); } }; }, onSet: FunctionStack.create(), onGet: FunctionStack.create(), // ???: would be nice to have a removeValue method // or maybe add an 'owner' property, combine with Janitor } // TODO: Janitor /* subscribe(subject, topic, listener); addCleanupTask(fn) cleanup(); */ MODEL({ name: 'Movement', methods: { distance: function(x, y) { return Math.sqrt(x*x + y*y); }, /** Combinator to create the composite of two functions. **/ o: function(f1, f2) { return function(x) { return f1(f2(x)); }; }, /** Combinator to create the average of two functions. **/ avg: function(f1, f2) { return function(x) { return (f1(x) + f2(x))/2; }; }, /** Constant speed. **/ linear: function(x) { return x; }, /** Move to target value and then return back to original value. **/ back: function(x) { return x < 0.5 ? 2*x : 2-2*x; }, /** Start slow and accelerate until half-way, then start slowing down. **/ accelerate: function(x) { return (Math.sin(x * Math.PI - Math.PI/2)+1)/2; }, /** Start slow and ease-in to full speed. **/ easeIn: function(a) { var v = 1/(1-a/2); return function(x) { var x1 = Math.min(x, a); var x2 = Math.max(x-a, 0); return (a ? 0.5*x1*(x1/a)*v : 0) + x2*v; }; }, /** Combinator to reverse behaviour of supplied function. **/ reverse: function(f) { return function(x) { return 1-f(1-x); }; }, /** Reverse of easeIn. **/ easeOut: function(b) { return Movement.reverse(Movement.easeIn(b)); }, /** * Cause an oscilation at the end of the movement. * @param b percentage of time to to spend bouncing [0, 1] * @param a amplitude of maximum bounce * @param opt_c number of cycles in bounce (default: 3) */ oscillate: function(b, a, opt_c) { var c = opt_c || 3; return function(x) { if ( x < (1-b) ) return x/(1-b); var t = (x-1+b)/b; return 1+(1-t)*2*a*Math.sin(2*c*Math.PI * t); }; }, /** * Cause an bounce at the end of the movement. * @param b percentage of time to to spend bouncing [0, 1] * @param a amplitude of maximum bounce */ bounce: function(b,a,opt_c) { var c = opt_c || 3; return function(x) { if ( x < (1-b) ) return x/(1-b); var t = (x-1+b)/b; return 1-(1-t)*2*a*Math.abs(Math.sin(2*c*Math.PI * t)); }; }, bounce2: function(a) { var v = 1 / (1-a); return function(x) { if ( x < (1-a) ) return v*x; var p = (x-1+a)/a; return 1-(x-1+a)*v/2; }; }, /** Move backwards a% before continuing to end. **/ stepBack: function(a) { return function(x) { return ( x < a ) ? -x : -2*a+(1+2*a)*x; }; }, /** Combination of easeIn and easeOut. **/ ease: function(a, b) { return Movement.o(Movement.easeIn(a), Movement.easeOut(b)); }, seq: function(f1, f2) { return ( f1 && f2 ) ? function() { f1.apply(this, argsToArray(arguments)); f2(); } : f1 ? f1 : f2 ; }, liveAnimations_: 0, /** @return a latch function which can be called to stop the animation. **/ animate: function(duration, fn, opt_interp, opt_onEnd, opt_X) { var requestAnimationFrameX = ( opt_X && opt_X.requestAnimationFrame ) || requestAnimationFrame; // console.assert( opt_X && opt_X.requestAnimationFrame, 'opt_X or opt_X.requestAnimationFrame not available'); if ( duration == 0 ) return Movement.seq(fn, opt_onEnd); var interp = opt_interp || Movement.linear; return function() { var ranges = []; var stopped = false; function stop() { var onEnd = opt_onEnd; if ( ! stopped ) { Movement.liveAnimations_--; stopped = true; onEnd && onEnd(); onEnd = null; if ( Movement.liveAnimations_ === 0 ) { var tasks = Movement.idleTasks_; if ( tasks && tasks.length > 0 ) { Movement.idleTasks_ = []; setTimeout(function() { // Since this is called asynchronously, there might be a new // animation. If so, queue up the tasks again. var i; if (Movement.liveAnimations_ > 0) { for ( i = 0 ; i < tasks.length ; i++ ) Movement.idleTasks_.push(tasks[i]); } else { for ( i = 0 ; i < tasks.length ; i++ ) tasks[i](); } }, 20); } } } } if ( fn ) { Events.onSet.push(function(obj, name, value2) { ranges.push([obj, name, obj[name], value2]); }); fn.apply(this, argsToArray(arguments)); Events.onSet.pop(); } var startTime = Date.now(); function go() { if ( stopped ) return; var now = Date.now(); var p = interp((Math.min(now, startTime + duration)-startTime)/duration); var last = now >= startTime + duration; for ( var i = 0 ; i < ranges.length ; i++ ) { var r = ranges[i]; var obj = r[0], name = r[1], value1 = r[2], value2 = r[3]; obj[name] = last ? value2 : value1 + (value2-value1) * p; } if ( last ) stop(); else requestAnimationFrameX(go); } if ( ranges.length > 0 ) { Movement.liveAnimations_++; requestAnimationFrameX(go); } else { var setTimeoutX = ( opt_X && opt_X.setTimeout ) || setTimeout; setTimeoutX(stop, duration); } return stop; }; }, whenIdle: function(fn) { // Decorate a function to defer execution until no animations are running return function() { if ( Movement.liveAnimations_ > 0 ) { if ( ! Movement.idleTasks_ ) Movement.idleTasks_ = []; var args = arguments; Movement.idleTasks_.push(function() { fn.apply(fn, args); }); } else { fn.apply(fn, arguments); } }; }, // requires unsubscribe to work first (which it does now) /* animate2: function(timer, duration, fn) { return function() { var startTime = timer.time; Events.onSet.push(function(obj, name, value2) { var value1 = obj[name]; Events.dynamic(function() { var now = timer.time; obj[name] = value1 + (value2-value1) * (now-startTime)/duration; if ( now > startTime + duration ) throw EventService.UNSUBSCRIBE_EXCEPTION; }); return false; }); fn.apply(this, argsToArray(arguments)); Events.onSet.pop(); update(); }; }, */ // TODO: if this were an object then you could sub-class to modify playback compile: function (a, opt_rest) { function noop() {} function isPause(op) { return Array.isArray(op) && op[0] == 0; } function compilePause(op, rest) { return function() { document.onclick = function() { document.onclick = null; rest(); }; }; } function isSimple(op) { return Array.isArray(op) && typeof op[0] === 'number'; } function compileSimple(op, rest) { op[3] = Movement.seq(op[3], rest); return function() { Movement.animate.apply(null, op)(); }; } function isParallel(op) { return Array.isArray(op) && Array.isArray(op[0]); } function compileParallel(op, rest) { var join = (function(num) { return function() { --num || rest(); }; })(op.length); return function() { for ( var i = 0 ; i < op.length ; i++ ) if ( isSimple(op[i]) ) Movement.animate(op[i][0], op[i][1], op[i][2], Movement.seq(op[i][3], join))(); else Movement.compile(op[i], join)(); }; } function compileFn(fn, rest) { return Movement.seq(fn, rest); } function compile_(a, i) { if ( i >= a.length ) return opt_rest || noop; var rest = compile_(a, i+1); var op = a[i]; if ( isPause(op) ) return compilePause(op, rest); if ( isSimple(op) ) return compileSimple(op, rest); if ( isParallel(op) ) return compileParallel(op, rest); return compileFn(op, rest); } return compile_(a, 0); }, onIntersect: function (o1, o2, fn) { if ( o1.model_.R ) { Events.dynamic(function() { o1.x; o1.y; o2.x; o2.y; }, function() { var dx = o1.x - o2.x; var dy = o1.y - o2.y; var d = dx*dx + dy*dy; var r2 = o1.r + o2.r; if ( d < r2*r2 ) fn.call(null, o1, o2); }); } else { Events.dynamic(function() { o1.x; o1.y; o2.x; o2.y; }, function() { if ( ( o1.x <= o2.x && o1.x + o1.width > o2.x && o1.y <= o2.y && o1.y + o1.height > o2.y ) || ( o2.x <= o1.x && o2.x + o2.width > o1.x && o2.y <= o1.y && o2.y + o2.height > o1.y ) ) { fn.call(null, o1, o2); } }); } }, stepTowards: function(src, dst, maxStep) { var dx = src.x - dst.x; var dy = src.y - dst.y; var theta = Math.atan2(dy,dx); var r = Math.sqrt(dx*dx+dy*dy); r = r < 0 ? Math.max(-maxStep, r) : Math.min(maxStep, r); dst.x += r*Math.cos(-theta); dst.y -= r*Math.sin(-theta); }, /** * Cause one object to move towards another at a specified rate. * * @arg t timer * @arg body body to be orbitted * @arg sat object to orbit body * @arg r radius of orbit * @arg p period of orbit */ moveTowards: function (t, body, sat, v) { var bodyX = body.propertyValue('x'); var bodyY = body.propertyValue('y'); var satX = sat.propertyValue('x'); var satY = sat.propertyValue('y'); t.addListener(function() { var dx = bodyX.get() - satX.get(); var dy = (bodyY.get() - satY.get()); var theta = Math.atan2(dy,dx); var r = Math.sqrt(dx*dx+dy*dy); r = r < 0 ? Math.max(-v, r) : Math.min(v, r); satX.set(satX.get() + r*Math.cos(-theta)); satY.set(satY.get() - r*Math.sin(-theta)); }); }, /** * Cause one object to orbit another. * * @arg t timer * @arg body body to be orbitted * @arg sat object to orbit body * @arg r radius of orbit * @arg p period of orbit */ orbit: function (t, body, sat, r, p, opt_start) { var bodyX = body.x$; var bodyY = body.y$; var satX = sat.x$; var satY = sat.y$; var start = opt_start || 0; t.addListener(EventService.framed(function() { var time = t.time; satX.set(bodyX.get() + r*Math.sin(time/p*Math.PI*2 + start)); satY.set(bodyY.get() + r*Math.cos(time/p*Math.PI*2 + start)); })); }, strut: function(mouse, c, dx, dy) { Events.dynamic(function() { mouse.x; mouse.y; }, function() { c.x = mouse.x + dx; c.y = mouse.y + dy; }); }, gravity: function(c, opt_a, opt_theta) { // TODO(kgr): implement opt_theta, the ability to control the direction var a = opt_a || 1; var theta = opt_theta || Math.PI * 1.5; Events.dynamic(function() { c.vx; c.vy; }, function() { c.vy += a; }); }, friction: function(c, opt_coef) { var coef = opt_coef || 0.9; Events.dynamic(function() { c.vx; c.vy; }, function() { c.vx = Math.abs(c.vx) < 0.001 ? 0 : c.vx * coef; c.vy = Math.abs(c.vy) < 0.001 ? 0 : c.vy * coef; }); }, inertia: function(c) { Events.dynamic(function() { c.vx; c.vy; c.x; c.y; }, function() { // Dynamic Friction if ( Math.abs(c.vx) > 0.001 ) c.x += c.vx; if ( Math.abs(c.vy) > 0.001 ) c.y += c.vy; // StaticFriction // if ( Math.abs(c.vx) < 0.001 ) c.vx = 0; // if ( Math.abs(c.vy) < 0.001 ) c.vy = 0; }); }, spring: function(mouse, c, dx, dy, opt_strength) { var strength = opt_strength || 6; var d = Movement.distance(dx, dy); Events.dynamic(function() { mouse.x; mouse.y; c.x; c.y; c.vx; c.vy; }, function() { if ( dx === 0 && dy === 0 ) { c.x = mouse.x; c.y = mouse.y; } else { var dx2 = mouse.x + dx - c.x; var dy2 = mouse.y + dy - c.y; var d2 = Movement.distance(dx2, dy2); var dv = strength * d2/d; if ( Math.abs(dv) < 0.01 ) return; var a = Math.atan2(dy2, dx2); c.vx += dv * Math.cos(a); c.vy += dv * Math.sin(a); } }); }, spring2: function(c1, c2, length, opt_strength) { var strength = opt_strength || 4; Events.dynamic(function() { c1.x; c1.y; c2.x; c2.y; }, function() { var d = c1.distanceTo(c2); var a = Math.atan2(c2.y-c1.y, c2.x-c1.x); if ( d > length ) { c1.applyMomentum( strength * (d/length-1), a); c2.applyMomentum(-strength * (d/length-1), a); } else if ( d < length ) { c1.applyMomentum(-strength * (length/d-1), a); c2.applyMomentum( strength * (length/d-1), a); } }); }, createAnimatedPropertyInstallFn: function(duration, interpolation) { /* Returns a function that can be assigned as a $$DOC{ref:'Property'} $$DOC{ref:'Property.install'} function. Any assignments to the property will be automatically animated.</p> <p><code> properties: [ &nbsp;&nbsp; { name: 'myProperty', &nbsp;&nbsp;&nbsp;&nbsp; install: createAnimatedPropertyInstallFn(500, Movement.ease(0.2, 0.2)), &nbsp;&nbsp;&nbsp;&nbsp; ... &nbsp;&nbsp; }] </code>*/ return function(prop) { this.defineProperty( { name: prop.name+"$AnimationLatch", defaultValue: 0, hidden: true, documentation: function() { /* The animation controller. */ }, } ); var actualSetter = this.__lookupSetter__(prop.name); this.defineProperty( { name: prop.name+"$AnimationSetValue", defaultValue: 0, hidden: true, documentation: function() { /* The animation value setter. */ }, postSet: function(_, nu) { actualSetter.call(this, nu); } } ); // replace setter with animater this.__defineSetter__(prop.name, function(nu) { // setter will be called on the instance, so "this" is an instance now var latch = this[prop.name+"$AnimationLatch"] ; latch && latch(); var anim = Movement.animate( duration, function() { this[prop.name+"$AnimationSetValue"] = nu; }.bind(this), interpolation ); this[prop.name+"$AnimationLatch"] = anim(); }); }; } } }); /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /** * JSONUtil -- Provides JSON++ marshalling support. * * Like regular JSON, with the following differences: * 1. Marshalls to/from FOAM Objects, rather than maps. * 2. Object Model information is encoded as 'model: "ModelName"' * 3. Default Values are not marshalled, saving disk space and network bandwidth. * 4. Support for marshalling functions. * 5. Support for property filtering, ie. only output non-transient properties. * 6. Support for 'pretty' and 'compact' modes. * * TODO: * Replace with JSONParser.js, when finished. * Maybe rename to FON (FOAM Object Notation, pronounced 'phone') to avoid * confusion with regular JSON syntax. **/ var AbstractFormatter = { keyify: function(str) { return '"' + str + '"'; }, stringify: function(obj) { var buf = ''; this.output(function() { for (var i = 0; i < arguments.length; i++) buf += arguments[i]; }, obj); return buf; }, stringifyObject: function(obj, opt_defaultModel) { var buf = ''; this.outputObject_(function() { for (var i = 0; i < arguments.length; i++) buf += arguments[i]; }, obj, opt_defaultModel); return buf; }, /** @param p a predicate function or an mLang **/ where: function(p) { return { __proto__: this, p: ( p.f && p.f.bind(p) ) || p }; }, p: function() { return true; } }; var JSONUtil = { escape: function(str) { return str .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/[\x00-\x1f]/g, function(c) { return "\\u00" + ((c.charCodeAt(0) < 0x10) ? '0' + c.charCodeAt(0).toString(16) : c.charCodeAt(0).toString(16)); }); }, parseToMap: function(str) { return eval('(' + str + ')'); }, parse: function(X, str, seq) { return this.mapToObj(X, this.parseToMap(str), undefined, seq); }, arrayToObjArray: function(X, a, opt_defaultModel, seq) { for ( var i = 0 ; i < a.length ; i++ ) { if ( ( ! DEBUG ) && a[i].debug ) { a.splice(i,1); i--; } else { a[i] = this.mapToObj(X, a[i], opt_defaultModel, seq); } } return a; }, /** * Convert JS-Maps which contain the 'model_' property, into * instances of that model. **/ mapToObj: function(X, obj, opt_defaultModel, seq) { if ( ! obj || typeof obj.model_ === 'object' ) return obj; if ( Array.isArray(obj) ) return this.arrayToObjArray(X, obj, undefined, seq); if ( obj instanceof Function ) return obj; if ( obj instanceof Date ) return obj; if ( obj instanceof Object ) { var j = 0; for ( var key in obj ) { if ( key != 'model_' && key != 'prototype_' ) obj[key] = this.mapToObj(X, obj[key], null, seq); j++; } if ( opt_defaultModel && ! obj.model_ ) return opt_defaultModel.create(obj); if ( obj.model_ ) { var newObj = X.lookup(obj.model_); if ( ( ! newObj || ! newObj.finished__ ) ) { var future = afuture(); seq && seq.push(future.get); arequire(obj.model_, X)(function(model) { if ( ! model ) { if ( DEBUG && obj.model_ !== 'Template' && obj.model_ !== 'ArrayProperty' && obj.model_ !== 'ViewFactoryProperty' && obj.model_ !== 'Documentation' && obj.model_ !== 'DocumentationProperty' && obj.model_ !== 'CSSProperty' && obj.model_ !== 'FunctionProperty' ) console.warn('Failed to dynamically load: ', obj.model_); future.set(obj); return; } var tmp = model.create(obj); obj.become(tmp); future.set(obj); }); return obj; } return newObj ? newObj.create(obj, X) : obj; } return obj } return obj; }, compact: { __proto__: AbstractFormatter, output: function(out, obj, opt_defaultModel) { if ( Array.isArray(obj) ) { this.outputArray_(out, obj); } else if ( typeof obj === 'string' ) { out('"'); out(JSONUtil.escape(obj)); out('"'); } else if ( obj instanceof Function ) { this.outputFunction_(out, obj); } else if ( obj instanceof Date ) { out(obj.getTime()); } else if ( obj instanceof RegExp ) { out(obj.toString()); } else if ( obj instanceof Object ) { if ( obj.model_ ) this.outputObject_(out, obj, opt_defaultModel); else this.outputMap_(out, obj); } else if ( typeof obj === 'number' ) { if ( ! isFinite(obj) ) obj = null; out(obj); } else { out(obj === undefined ? null : obj); } }, outputObject_: function(out, obj, opt_defaultModel) { var str = ''; var first = true; out('{'); if ( obj.model_.id !== opt_defaultModel ) { this.outputModel_(out, obj); first = false; } var properties = obj.model_.getRuntimeProperties(); for ( var key in properties ) { var prop = properties[key]; if ( ! this.p(prop) ) continue; if ( prop.name in obj.instance_ ) { var val = obj[prop.name]; if ( Array.isArray(val) && ! val.length ) continue; if ( ! first ) out(','); out(this.keyify(prop.name), ': '); if ( Array.isArray(val) && prop.subType ) { this.outputArray_(out, val, prop.subType); } else { this.output(out, val); } first = false; } } out('}'); }, outputModel_: function(out, obj) { out('model_:"') if ( obj.model_.package ) out(obj.model_.package, '.') out(obj.model_.name, '"'); }, outputMap_: function(out, obj) { var str = ''; var first = true; out('{'); for ( var key in obj ) { var val = obj[key]; if ( ! first ) out(','); out(this.keyify(key), ': '); this.output(out, val); first = false; } out('}'); }, outputArray_: function(out, a, opt_defaultModel) { if ( a.length == 0 ) { out('[]'); return out; } var str = ''; var first = true; out('['); for ( var i = 0 ; i < a.length ; i++, first = false ) { var obj = a[i]; if ( ! first ) out(','); this.output(out, obj, opt_defaultModel); } out(']'); }, outputFunction_: function(out, obj) { out(obj); } }, pretty: { __proto__: AbstractFormatter, output: function(out, obj, opt_defaultModel, opt_indent) { var indent = opt_indent || ''; if ( Array.isArray(obj) ) { this.outputArray_(out, obj, null, indent); } else if ( typeof obj == 'string' ) { out('"'); out(JSONUtil.escape(obj)); out('"'); } else if ( obj instanceof Function ) { this.outputFunction_(out, obj, indent); } else if ( obj instanceof Date ) { out(obj.getTime()); } else if ( obj instanceof RegExp ) { out(obj.toString()); } else if ( obj instanceof Object ) { if ( obj.model_ ) this.outputObject_(out, obj, opt_defaultModel, indent); else this.outputMap_(out, obj, indent); } else if ( typeof obj === 'number' ) { if ( ! isFinite(obj) ) obj = null; out(obj); } else { if ( obj === undefined ) obj = null; out(obj); } }, outputObject_: function(out, obj, opt_defaultModel, opt_indent) { var indent = opt_indent || ''; var nestedIndent = indent + ' '; var str = ''; var first = true; out(/*"\n", */indent, '{\n'); if ( obj.model_.id && obj.model_.id !== opt_defaultModel ) { this.outputModel_(out, obj, nestedIndent); first = false; } var properties = obj.model_.getRuntimeProperties(); for ( var key in properties ) { var prop = properties[key]; if ( ! this.p(prop) ) continue; if ( prop.name === 'parent' ) continue; if ( prop.name in obj.instance_ ) { var val = obj[prop.name]; if ( Array.isArray(val) && ! val.length ) continue; if ( ! first ) out(',\n'); out(nestedIndent, this.keyify(prop.name), ': '); if ( Array.isArray(val) && prop.subType ) { this.outputArray_(out, val, prop.subType, nestedIndent); } else { this.output(out, val, null, nestedIndent); } first = false; } } out('\n', indent, '}'); }, outputModel_: function(out, obj, indent) { out(indent, '"model_": "', obj.model_.id, '"'); }, outputMap_: function(out, obj, opt_indent) { var indent = opt_indent || ''; var nestedIndent = indent + ' '; var str = ''; var first = true; out(/*"\n",*/ indent, '{\n', nestedIndent); for ( var key in obj ) { var val = obj[key]; if ( ! first ) out(',\n'); out(nestedIndent, this.keyify(key), ': '); this.output(out, val, null, nestedIndent); first = false; } out('\n', indent, '}'); }, outputArray_: function(out, a, opt_defaultModel, opt_indent) { if ( a.length == 0 ) { out('[]'); return out; } var indent = opt_indent || ''; var nestedIndent = indent + ' '; var str = ''; var first = true; out('[\n'); for ( var i = 0 ; i < a.length ; i++, first = false ) { var obj = a[i]; if ( ! first ) out(',\n'); this.output(out, obj, opt_defaultModel, nestedIndent); } out('\n', indent, ']'); }, outputFunction_: function(out, obj, indent) { var str = obj.toString(); var lines = str.split('\n'); if ( lines.length == 1 ) { out(str); return; } var minIndent = 10000; for ( var i = 0 ; i < lines.length ; i++ ) { var j = 0; for ( ; j < lines[i].length && lines[i].charAt(j) === ' ' && j < minIndent ; j++ ); if ( j > 0 && j < minIndent ) minIndent = j; } if ( minIndent === 10000 ) { out(str); return; } for ( var i = 0 ; i < lines.length ; i++ ) { if ( lines[i].length && lines[i].charAt(0) === ' ' ) { lines[i] = indent + lines[i].substring(minIndent); } out(lines[i]); if ( i < lines.length-1 ) out('\n'); } } }, moreCompact: { __proto__: AbstractFormatter, // TODO: use short-names }, compressed: { __proto__: AbstractFormatter, stringify: function(obj) { return Iuppiter.Base64.encode(Iuppiter.compress(JSONUtil.compact.stringify(obj),true)); } } }; JSONUtil.prettyModel = { __proto__: JSONUtil.pretty, outputModel_: function(out, obj, indent) { out(indent, 'model_: "', obj.model_.id, '"'); }, keys_: {}, keyify: function(str) { if ( ! this.keys_.hasOwnProperty(str) ) { this.keys_[str] = /^[a-zA-Z\$_][0-9a-zA-Z$_]*$/.test(str) ? str : '"' + str + '"'; } return this.keys_[str]; } }; JSONUtil.stringify = JSONUtil.pretty.stringify.bind(JSONUtil.pretty); JSONUtil.stringifyObject = JSONUtil.pretty.stringifyObject.bind(JSONUtil.pretty); JSONUtil.output = JSONUtil.pretty.output.bind(JSONUtil.pretty); JSONUtil.where = JSONUtil.pretty.where.bind(JSONUtil.pretty); var NOT_TRANSIENT = function(prop) { return ! prop.transient; }; /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ var XMLParser = { __proto__: grammar, START: seq1(1, sym('whitespace'), sym('tag'), sym('whitespace')), tag: seq( '<', sym('tagName'), sym('whitespace'), repeat(sym('attribute'), sym('whitespace')), sym('whitespace'), '>', repeat(alt( sym('tag'), sym('text') )), '</', sym('tagName'), '>' ), label: str(plus(notChars(' =/\t\r\n<>\'"'))), tagName: sym('label'), text: str(plus(notChar('<'))), attribute: seq(sym('label'), '=', sym('value')), value: str(alt( seq1(1, '"', repeat(notChar('"')), '"'), seq1(1, "'", repeat(notChar("'")), "'") )), whitespace: repeat(alt(' ', '\t', '\r', '\n')) }; XMLParser.addActions({ // Trying to abstract all the details of the parser into one place, // and to use a more generic representation in XMLUtil.parse(). tag: function(xs) { // < label ws attributes ws > children </ label > // 0 1 2 3 4 5 6 7 8 9 // Mismatched XML tags // TODO: We should be able to set the error message on the ps here. if ( xs[1] != xs[8] ) return undefined; var obj = { tag: xs[1], attrs: {}, children: xs[6] }; xs[3].forEach(function(attr) { obj.attrs[attr[0]] = attr[2]; }); return obj; } }); var XMLUtil = { escape: function(str) { return str && str.toString() .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); }, unescape: function(str) { return str && str.toString() .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&amp;/g, '&'); }, escapeAttr: function(str) { return str && str.replace(/"/g, '&quot;'); }, unescapeAttr: function(str) { return str && str.replace(/&quot;/g, '"'); }, parse: function(str) { var result = XMLParser.parseString(str); if ( ! result ) return result; // Parse error on undefined. // Otherwise result is the <foam> tag. return this.parseArray(result.children); }, parseObject: function(tag) { var obj = {}; var self = this; tag.children.forEach(function(c) { // Ignore children which are not tags. if (typeof c === 'object' && c.attrs && c.attrs.name) { var result; if ( c.attrs.type && c.attrs.type == 'function' ) { var code = XMLUtil.unescape(c.children.join('')); if ( code.startsWith('function') ) { result = eval('(' + code + ')'); } else { result = new Function(code); } } else { result = self.parseArray(c.children); } obj[self.unescapeAttr(c.attrs.name)] = result; } }); if ( !tag.attrs.model ) return obj; var model = this.unescapeAttr(tag.attrs.model); return GLOBAL[model] ? GLOBAL[model].create(obj) : obj; }, parseArray: function(a) { // Turn <i> tags into primitive values, everything else goes through // parseObject. // Any loose primitive values are junk whitespace, and ignored. var self = this; var ret = []; a.forEach(function(x) { if ( typeof x !== 'object' ) return; if ( x.tag == 'i' ) { ret.push(XMLUtil.unescape(x.children[0])); // Literal content. } else { ret.push(self.parseObject(x)); } }); // Special case: If we found nothing, return all children as a string. return ret.length ? ret : XMLUtil.unescape(a.join('')); }, compact: { stringify: function(obj) { var buf = []; this.output(buf.push.bind(buf), obj); return '<foam>' + buf.join('') + '</foam>'; }, output: function(out, obj) { if ( Array.isArray(obj) ) { this.outputArray_(out, obj); } else if ( typeof obj == 'string' ) { out(XMLUtil.escape(obj)); } else if ( obj instanceof Function ) { this.outputFunction_(out, obj); } else if ( obj instanceof Object ) { if ( obj.model_ ) this.outputObject_(out, obj); else this.outputMap_(out, obj); } else { out(obj); } }, outputObject_: function(out, obj) { out('<object model="', XMLUtil.escapeAttr(obj.model_.name), '">'); var properties = obj.model_.getRuntimeProperties(); for ( var key in properties ) { var prop = properties[key]; if ( prop.name === 'parent' ) continue; if ( obj.instance_ && prop.name in obj.instance_ ) { var val = obj[prop.name]; if ( Array.isArray(val) && val.length == 0 ) continue; if ( val == prop.defaultValue ) continue; out('<property name="', XMLUtil.escapeAttr(prop.name), '" ' + (typeof val === 'function' ? 'type="function"' : '') + '>'); this.output(out, val); out('</property>'); } } out('</object>'); }, outputMap_: function(out, obj) { out('<object>'); for ( var key in obj ) { var val = obj[key]; out('<property name="', XMLUtil.escapeAttr(key), '">'); this.output(out, val); out('</property>'); } out('</object>'); }, outputArray_: function(out, a) { if ( a.length == 0 ) return out; for ( var i = 0 ; i < a.length ; i++, first = false ) { var obj = a[i]; if (typeof obj === 'string' || typeof obj === 'number') out('<i>', XMLUtil.escape(obj), '</i>'); else this.output(out, obj); } }, outputFunction_: function(out, f) { out(XMLUtil.escape(f.toString())); } }, pretty: { stringify: function(obj) { var buf = []; this.output(buf.push.bind(buf), obj); return '<foam>\n' + buf.join('') + '</foam>\n'; }, output: function(out, obj, opt_indent) { var indent = opt_indent || ""; if ( Array.isArray(obj) ) { this.outputArray_(out, obj, indent); } else if ( typeof obj == 'string' ) { out(XMLUtil.escape(obj)); } else if ( obj instanceof Function ) { this.outputFunction_(out, obj, indent); } else if ( obj instanceof Object ) { try { if ( obj.model_ && typeof obj.model_ !== 'string' ) this.outputObject_(out, obj, indent); else this.outputMap_(out, obj, indent); } catch (x) { console.log('toXMLError: ', x); } } else { out(obj); } }, outputObject_: function(out, obj, opt_indent) { var indent = opt_indent || ""; var nestedIndent = indent + " "; out(indent, '<object model="', XMLUtil.escapeAttr(obj.model_.name), '">'); var properties = obj.model_.getRuntimeProperties(); for ( var key in properties ) { var prop = properties[key]; if ( prop.name === 'parent' ) continue; if ( obj.instance_ && prop.name in obj.instance_ ) { var val = obj[prop.name]; if ( Array.isArray(val) && val.length == 0 ) continue; if ( val == prop.defaultValue ) continue; var type = typeof obj[prop.name] == 'function' ? ' type="function"' : ''; out("\n", nestedIndent, '<property name="', XMLUtil.escapeAttr(prop.name), '"', type, '>'); this.output(out, val, nestedIndent); out('</property>'); } } out('\n', indent, '</object>'); out('\n'); }, outputMap_: function(out, obj, opt_indent) { var indent = opt_indent || ""; var nestedIndent = indent + " "; out(indent, '<object>'); for ( var key in obj ) { var val = obj[key]; out("\n", nestedIndent, '<property name="', XMLUtil.escapeAttr(key), '">'); this.output(out, val, nestedIndent); out('</property>'); } out("\n", indent, '</object>\n'); }, outputArray_: function(out, a, opt_indent) { if ( a.length == 0 ) return out; var indent = opt_indent || ""; var nestedIndent = indent + " "; for ( var i = 0 ; i < a.length ; i++, first = false ) { var obj = a[i]; out('\n'); if (typeof obj === 'string' || typeof obj === 'number') out(nestedIndent, '<i>', XMLUtil.escape(obj), '</i>'); else this.output(out, obj, nestedIndent); } out('\n',indent); }, outputFunction_: function(out, f, opt_indent) { out(XMLUtil.escape(f.toString()) + '\n' + (opt_indent || '')); } } }; XMLUtil.stringify = XMLUtil.pretty.stringify.bind(XMLUtil.pretty); XMLUtil.output = XMLUtil.pretty.output.bind(XMLUtil.pretty);; /** * @license * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ GLOBAL.lookupCache_ = {}; function lookup(key) { if ( ! key ) return undefined; if ( ! ( typeof key === 'string' ) ) return key; var root = this var cache; // if ( this.hasOwnProperty('lookupCache_') ) { cache = this.lookupCache_; // } else { // cache = this.lookupCache_ = {}; // } var ret = cache[key]; if ( ret === undefined ) { var path = key.split('.'); for ( var i = 0 ; root && i < path.length ; i++ ) root = root[path[i]]; ret = root; cache[key] = ret ? ret : null; // implements negative-caching } return ret; } /** Update a Context binding. **/ function set(key, value) { // It looks like the chrome debug console is overwriting sub.window // but this prevents it. Object.defineProperty( this, key, { value: value, writable: key !== 'window', configurable: true } ); } function setValue(key, value) { var X = this; Object.defineProperty( this, key, { get: function() { X.set(key, value.get()); return X[key]; }, configurable: true } ); } /** Create a sub-context, populating with bindings from opt_args. **/ function sub(opt_args, opt_name) { var sub = Object.create(this); if ( opt_args ) for ( var key in opt_args ) { if ( opt_args.hasOwnProperty(key) ) { sub.set(key, opt_args[key]); } } if ( opt_name ) { sub.NAME = opt_name; // This was commented out because it appears to be very slow // sub.toString = function() { return 'CONTEXT(' + opt_name + ')'; }; // sub.toString = function() { return 'CONTEXT(' + opt_name + ', ' + this.toString() + ')'; }; } // console.assert(this.lookupCache_, 'Missing cache.'); // sub.lookupCache_ = Object.create(this.lookupCache_); return sub; } function subWindow(w, opt_name, isBackground) { if ( ! w ) return this.sub(); return foam.ui.Window.create({window: w, name: opt_name, isBackground: isBackground}, this).Y; } var X = sub({}); var foam = X.foam = {}; var registerFactory = function(model, factory) { // TODO }; var registerModelForModel = function(modelType, targetModel, model) { }; var registerFactoryForModel = function(factory, targetModel, model) { }; /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /** * JSON Parser. */ var JSONParser = SkipGrammar.create({ __proto__: grammar, START: copyInput(sym('objAsString')), objAsString: copyInput(sym('obj')), obj: seq1(1, '{', repeat(sym('pair'), ','), '}'), pair: seq(sym('key'), ':', sym('value')), key: alt( sym('symbol'), sym('string')), symbol: noskip(str(seq(sym('char'), str(repeat(sym('alpha')))))), char: alt(range('a','z'), range('A','Z'), '_', '$'), // Slightly faster to inline sym('char') until AltParser does it automatically alpha: alt(range('a','z'), range('A','Z'), '_', '$', /* sym('char') */ range('0', '9')), // TODO(kgr): This should just be 'alt' but that isn't working for some // unknown reason. Probably related to SkipGrammar. Fix and change to // just 'alt'. value: simpleAlt( sym('function literal'), sym('expr'), sym('number'), sym('string'), sym('obj'), sym('bool'), sym('array') ), expr: str(seq( sym('symbol'), optional(str(alt( seq('.', sym('expr')), seq('(', str(repeat(sym('value'), ',')), ')')))))), number: noskip(seq( optional('-'), repeat(range('0', '9'), null, 1), optional(seq('.', repeat(range('0', '9')))))), string: noskip(alt( sym('single quoted string'), sym('double quoted string'))), 'double quoted string': seq1(1, '"', str(repeat(sym('double quoted char'))), '"'), 'double quoted char': alt( sym('escape char'), literal('\\"', '"'), notChar('"')), 'single quoted string': seq1(1, "'", str(repeat(sym('single quoted char'))), "'"), 'single quoted char': alt( sym('escape char'), literal("\\'", "'"), notChar("'")), 'escape char': alt( literal('\\\\', '\\'), literal('\\n', '\n')), bool: alt( literal('true', true), literal('false', false)), array: seq1(1, '[', repeat(sym('value'), ','), ']'), 'function literal': seq( 'function', optional(sym('symbol')), '(', repeat(sym('symbol'), ','), ')', '{', repeat(notChar('}')), // TODO(kgr): this is a very cheap/limited hack, replace with real JS grammar. // repeat(sym('value'), ';'), // TODO(kgr): replace with 'statement'. '}') }.addActions({ obj: function(v) { var m = {}; for ( var i = 0 ; i < v.length ; i++ ) m[v[i][0]] = v[i][2]; return m; } }), repeat0(alt(' ', '\t', '\n', '\r'))); /* TODO: move to FUNTest var res = JSONParser.parseString('{a:1,b:"2",c:false,d:f(),e:g(1,2),f:h.j.k(1),g:[1,"a",false,[]]}'); console.log(res); */ /** * @license * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /** * Simple template system modelled after JSP's. * * Syntax: * <% code %>: code inserted into template, but nothing implicitly output * <%= comma-separated-values %>: all values are appended to template output * <%# expression %>: dynamic (auto-updating) expression is output * \<new-line>: ignored * %%value(<whitespace>|<): output a single value to the template output * $$feature(<whitespace>|<): output the View or Action for the current Value */ MODEL({ name: 'TemplateParser', extendsModel: 'grammar', methods: { START: sym('markup'), markup: repeat0(alt( sym('comment'), sym('foamTag'), sym('create child'), sym('simple value'), sym('live value tag'), sym('raw values tag'), sym('values tag'), sym('code tag'), sym('ignored newline'), sym('newline'), sym('single quote'), sym('text') )), 'comment': seq1(1, '<!--', repeat0(not('-->', anyChar)), '-->'), 'foamTag': sym('foamTag_'), 'foamTag_': function() { }, // placeholder until gets filled in after HTMLParser is built 'create child': seq( '$$', repeat(notChars(' $\n<{')), optional(JSONParser.export('objAsString'))), 'simple value': seq('%%', repeat(notChars(' ()-"\n><:;,')), optional('()')), 'live value tag': seq('<%#', repeat(not('%>', anyChar)), '%>'), 'raw values tag': alt( seq('<%=', repeat(not('%>', anyChar)), '%>'), seq('{{{', repeat(not('}}}', anyChar)), '}}}') ), 'values tag': seq('{{', repeat(not('}}', anyChar)), '}}'), 'code tag': seq('<%', repeat(not('%>', anyChar)), '%>'), 'ignored newline': literal('\\\n'), newline: literal('\n'), 'single quote': literal("'"), text: anyChar } }); var TemplateOutput = { /** * obj - Parent object. If objects are output and have an initHTML() method, then they * are added to the parent by calling obj.addChild(). **/ // TODO(kgr): redesign, I think this is actually broken. If we call appendHTML() of // a sub-view then it will be added to the wrong parent. create: function(obj) { var buf = []; var f = function templateOut(/* arguments */) { for ( var i = 0 ; i < arguments.length ; i++ ) { var o = arguments[i]; if ( typeof o === 'string' ) { buf.push(o); } else { if ( o && o.toView_ ) o = o.toView_(); if ( ! ( o === null || o === undefined ) ) { if ( o.appendHTML ) { o.appendHTML(this); } else if ( o.toHTML ) { buf.push(o.toHTML()); } else { buf.push(o); } if ( o.initHTML && obj && obj.addChild ) obj.addChild(o); } } } }; f.toString = function() { if ( buf.length === 0 ) return ''; if ( buf.length > 1 ) buf = [buf.join('')]; return buf[0]; } return f; } }; // Called from generated template code. function elementFromString(str) { return str.element || ( str.element = HTMLParser.create().parseString(str).children[0] ); } var ConstantTemplate = function(str) { var TemplateOutputCreate = TemplateOutput.create.bind(TemplateOutput); var f = function(opt_out) { var out = opt_out ? opt_out : TemplateOutputCreate(this); out(str); return out.toString(); }; f.toString = function() { return 'ConstantTemplate("' + str.replace(/\n/g, "\\n").replace(/"/g, '\\"') + '")'; }; return f; }; var TemplateCompiler = { __proto__: TemplateParser, out: [], simple: true, // True iff the template is just one string literal. push: function() { this.simple = false; this.pushSimple.apply(this, arguments); }, pushSimple: function() { this.out.push.apply(this.out, arguments); }, header: 'var self = this, X = this.X, Y = this.Y;' + 'var out = opt_out ? opt_out : TOC(this);' + "out('", footer: "');" + "return out.toString();" }.addActions({ markup: function (v) { var wasSimple = this.simple; var ret = wasSimple ? null : this.header + this.out.join('') + this.footer ; this.out = []; this.simple = true; return [wasSimple, ret]; }, 'create child': function(v) { var name = v[1].join(''); this.push( "', self.createTemplateView('", name, "'", v[2] ? ', ' + v[2] : '', "),\n'"); }, foamTag: function(e) { // A Feature var fName = e.getAttribute('f'); if ( fName ) { this.push("', self.createTemplateView('", fName, "',{}).fromElement(FOAM("); this.push(JSONUtil.where(NOT_TRANSIENT).stringify(e)); this.push('))'); } // A Model else { this.push("', (function() { var tagView = X.foam.ui.FoamTagView.create({element: FOAM("); this.push(JSONUtil.where(NOT_TRANSIENT).stringify(e)); this.push(')}, Y); self.addDataChild(tagView); return tagView; })() '); } this.push(",\n'"); }, 'simple value': function(v) { this.push("',\n self.", v[1].join(''), v[2], ",\n'"); }, 'raw values tag': function (v) { this.push("',\n", v[1].join(''), ",\n'"); }, 'values tag': function (v) { this.push("',\nescapeHTML(", v[1].join(''), "),\n'"); }, 'live value tag': function (v) { this.push("',\nself.dynamicTag('span', function() { return ", v[1].join(''), "; }.bind(this)),\n'"); }, 'code tag': function (v) { this.push("');\n", v[1].join(''), ";out('"); }, 'single quote': function () { this.pushSimple("\\'"); }, newline: function () { this.pushSimple('\\n'); }, text: function(v) { this.pushSimple(v); } }); MODEL({ name: 'TemplateUtil', methods: { /** Create a method which only compiles the template when first used. **/ lazyCompile: function(t) { var delegate; var f = function() { if ( ! delegate ) { if ( ! t.template ) throw 'Must arequire() template model before use for ' + this.name_ + '.' + t.name; else delegate = TemplateUtil.compile(Template.isInstance(t) ? t : Template.create(t)); } return delegate.apply(this, arguments); }; f.toString = function() { return delegate ? delegate.toString() : t.toString(); }; return f; }, compile_: function(t, code) { var args = ['opt_out']; for ( var i = 0 ; i < t.args.length ; i++ ) { args.push(t.args[i].name); } return eval('(function() { var escapeHTML = XMLUtil.escape, TOC = TemplateOutput.create.bind(TemplateOutput); return function(' + args.join(',') + '){' + code + '};})()'); }, compile: function(t) { // console.time('parse-template-' + t.name); var code = TemplateCompiler.parseString(t.template); // console.timeEnd('parse-template-' + t.name); // Simple case, just a string literal if ( code[0] ) return ConstantTemplate(t.template); // Need to compile an actual method try { return this.compile_(t, code[1]); } catch (err) { console.log('Template Error: ', err); console.log(code); return function() {}; } }, /** * Combinator which takes a template which expects an output parameter and * converts it into a function which returns a string. */ stringifyTemplate: function (template) { return function() { var buf = []; this.output(buf.push.bind(buf), obj); return buf.join(''); }; }, expandTemplate: function(self, t, opt_X) { /* * If a template is supplied as a function, treat it as a multiline string. * Parse function arguments to populate template.args. * Load template from file if external. * Setup template future. */ var X = opt_X || self.X; if ( typeof t === 'function' ) { t = X.Template.create({ name: t.name, // ignore first argument, which should be 'opt_out' args: t.toString().match(/\((.*?)\)/)[1].split(',').slice(1).map(function(a) { return X.Arg.create({name: a.trim()}); }), template: multiline(t)}); } else if ( typeof t === 'string' ) { t = docTemplate = X.Template.create({ name: 'body', template: t }); } else if ( ! t.template && ! t.code ) { var future = afuture(); var path = self.sourcePath; t.futureTemplate = future.get; path = path.substring(0, path.lastIndexOf('/')+1); path += self.name + '_' + t.name + '.ft'; if ( window.XMLHttpRequest ) { var xhr = new XMLHttpRequest(); xhr.open("GET", path); xhr.asend(function(data) { t.template = data; future.set(Template.create(t)); }); } else { var fs = require('fs'); fs.readFile(path, function(err, data) { t.template = data.toString(); future.set(Template.create(t)); }); } } else if ( typeof t.template === 'function' ) { t.template = multiline(t.template); } if ( ! t.futureTemplate ) t.futureTemplate = aconstant(t); // We haven't FOAMalized the template, and there's no crazy multiline functions. // Note that Model and boostrappy models must use this case, as Template is not // yet defined at bootstrap time. Use a Template object definition with a bare // string template body in those cases. if ( ! t.template$ ) { t = ( typeof X.Template !== 'undefined' ) ? JSONUtil.mapToObj(X, t, X.Template) : t ; } return t; }, expandModelTemplates: function(self) { var templates = self.templates; for ( var i = 0; i < templates.length; i++ ) { templates[i] = TemplateUtil.expandTemplate(self, templates[i]); } } } }); /** Is actually synchronous but is replaced in ChromeApp with an async version. **/ var aeval = function(src) { return aconstant(eval('(' + src + ')')); }; var aevalTemplate = function(t, model) { return aseq( t.futureTemplate, function(ret, t) { ret(TemplateUtil.lazyCompile(t)); }); }; var escapeHTML = XMLUtil.escape, TOC = TemplateOutput.create.bind(TemplateOutput); /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ var $documents = []; if ( window ) $documents.push(window.document); // TODO: clean this up, hide $WID__ in closure var $WID__ = 0; function $addWindow(w) { w.window.$WID = $WID__++; $documents.push(w.document); } function $removeWindow(w) { for ( var i = $documents.length - 1 ; i >= 0 ; i-- ) { if ( ! $documents[i].defaultView || $documents[i].defaultView === w ) $documents.splice(i,1); } } /** Replacement for getElementById **/ // TODO(kgr): remove this is deprecated, use X.$ instead() var $ = function (id) { console.log('Deprecated use of GLOBAL.$.'); for ( var i = 0 ; i < $documents.length ; i++ ) { if ( document.FOAM_OBJECTS && document.FOAM_OBJECTS[id] ) return document.FOAM_OBJECTS[id]; var ret = $documents[i].getElementById(id); if ( ret ) return ret; } return undefined; }; /** Replacement for getElementByClassName **/ // TODO(kgr): remove this is deprecated, use X.$$ instead() var $$ = function (cls) { console.log('Deprecated use of GLOBAL.$$.'); for ( var i = 0 ; i < $documents.length ; i++ ) { var ret = $documents[i].getElementsByClassName(cls); if ( ret.length > 0 ) return ret; } return []; }; var FOAM = function(map, opt_X, seq) { var obj = JSONUtil.mapToObj(opt_X || X, map, undefined, seq); return obj; }; /** * Register a lazy factory for the specified name within a * specified context. * The first time the name is looked up, the factory will be invoked * and its value will be stored in the named slot and then returned. * Future lookups to the same slot will return the originally created * value. **/ FOAM.putFactory = function(ctx, name, factory) { ctx.__defineGetter__(name, function() { console.log('Bouncing Factory: ', name); delete ctx[name]; return ctx[name] = factory(); }); }; var USED_MODELS = {}; var UNUSED_MODELS = {}; var NONMODEL_INSTANCES = {}; // for things such as interfaces FOAM.browse = function(model, opt_dao, opt_X) { var Y = opt_X || X.sub(undefined, "FOAM BROWSER"); if ( typeof model === 'string' ) model = Y[model]; var dao = opt_dao || Y[model.name + 'DAO'] || Y[model.plural]; if ( ! dao ) { Y[model.name + 'DAO'] = [].dao; } var ctrl = Y.foam.ui.DAOController.create({ model: model, dao: dao, useSearchView: false }); if ( ! Y.stack ) { var w = opt_X ? opt_X.window : window; Y.stack = Y.foam.ui.StackView.create(); var win = Y.foam.ui.layout.Window.create({ window: w, data: Y.stack }, Y); document.body.insertAdjacentHTML('beforeend', win.toHTML()); win.initHTML(); Y.stack.setTopView(ctrl); } else { Y.stack.pushView(ctrl); } }; var arequire = function(modelName, opt_X) { var X = opt_X || GLOBAL.X; var model = X.lookup(modelName); if ( ! model ) { if ( ! X.ModelDAO ) { // if ( modelName !== 'Template' ) console.warn('Unknown Model in arequire: ', modelName); return aconstant(); } // check whether we have already hit the ModelDAO to load the model if ( ! X.arequire$ModelLoadsInProgress ) { X.set('arequire$ModelLoadsInProgress', {} ); } else { if ( X.arequire$ModelLoadsInProgress[modelName] ) { return X.arequire$ModelLoadsInProgress[modelName]; } } var future = afuture(); X.arequire$ModelLoadsInProgress[modelName] = future.get; X.ModelDAO.find(modelName, { put: function(m) { // Contextualize the model for this context m.X = X; m.arequire()(function(m) { X.arequire$ModelLoadsInProgress[modelName] = false; X.registerModel(m); future.set(m); }); }, error: function() { var args = argsToArray(arguments); console.warn.apply(console, ['Could not load model: ', modelName].concat(args)); X.arequire$ModelLoadsInProgress[modelName] = false; future.set(undefined); } }); return future.get; } return model.arequire() } var FOAM_POWERED = '<a style="text-decoration:none;" href="https://github.com/foam-framework/foam/" target="_blank">\ <font size=+1 face="catull" style="text-shadow:rgba(64,64,64,0.3) 3px 3px 4px;">\ <font color="#3333FF">F</font><font color="#FF0000">O</font><font color="#FFCC00">A</font><font color="#33CC00">M</font>\ <font color="#555555" > POWERED</font></font></a>'; /** Lookup a '.'-separated package path, creating sub-packages as required. **/ function packagePath(X, path) { function packagePath_(Y, path, i) { if ( i === path.length ) return Y; if ( ! Y[path[i]] ) { Y[path[i]] = {}; // console.log('************ Creating sub-path: ', path[i]); if ( i == 0 ) GLOBAL[path[i]] = Y[path[i]]; } return packagePath_(Y[path[i]], path, i+1); } return path ? packagePath_(X, path.split('.'), 0) : GLOBAL; } function registerModel(model, opt_name, fastMode) { var root = model.package ? this : GLOBAL; var name = model.name; var package = model.package; if ( opt_name ) { var a = opt_name.split('.'); name = a.pop(); package = a.join('.'); } var path = packagePath(root, package); if ( fastMode ) path[name] = model; else Object.defineProperty(path, name, { value: model, configurable: true }); // TODO: this is broken // update the cache if this model was already FOAM.lookup'd if ( root.lookupCache_ ) { var cache = root.lookupCache_; var modelRegName = (package ? package + '.' : '') + name; // if ( cache[modelRegName] ) { // console.log("registerModel: in lookupCache_, replaced model ", modelRegName ); cache[modelRegName] = model; // } } this.onRegisterModel(model); } var CLASS = function(m) { // Don't Latch these Models, as we know that we'll need them on startup var EAGER = { 'Method': true, 'BooleanProperty': true, 'Action': true, 'FunctionProperty': true, 'Constant': true, 'Message': true, 'ArrayProperty': true, 'StringArrayProperty': true, 'Template': true, 'Arg': true, 'Relationship': true, 'ViewFactoryProperty': true, 'FactoryProperty': true, 'foam.ui.Window': true, 'StringProperty': true, 'foam.html.Element': true, 'Expr': true, 'AbstractDAO': true }; /** Lazily create and register Model first time it's accessed. **/ function registerModelLatch(path, m) { var id = m.package ? m.package + '.' + m.name : m.name; if ( EAGER[id] ) { USED_MODELS[id] = true; var work = []; var model = JSONUtil.mapToObj(X, m, Model, work); if ( work.length > 0 ) { model.extra__ = aseq.apply(null, work); } X.registerModel(model, undefined, true); return model; } GLOBAL.lookupCache_[id] = undefined; UNUSED_MODELS[id] = true; var triggered = false; //console.log("Model Getting defined: ", m.name, X.NAME); Object.defineProperty(m.package ? path : GLOBAL, m.name, { get: function triggerModelLatch() { if ( triggered ) return null; triggered = true; // console.time('registerModel: ' + id); USED_MODELS[id] = true; UNUSED_MODELS[id] = undefined; var work = []; // console.time('buildModel: ' + id); var model = JSONUtil.mapToObj(X, m, Model, work); // console.timeEnd('buildModel: ' + id); if ( work.length > 0 ) { model.extra__ = aseq.apply(null, work); } X.registerModel(model); // console.timeEnd('registerModel: ' + id); return model; }, configurable: true }); } if ( document && document.currentScript ) m.sourcePath = document.currentScript.src; registerModelLatch(packagePath(X, m.package), m); } var MODEL = CLASS; function INTERFACE(imodel) { // Unless in DEBUG mode, just discard interfaces as they're only used for type checking. // if ( ! DEBUG ) return; var i = JSONUtil.mapToObj(X, imodel, Interface); packagePath(X, i.package)[i.name] = i; var id = i.package ? i.package + '.' + i.name : i.name; NONMODEL_INSTANCES[id] = true; } /** Called when a Model is registered. **/ function onRegisterModel(m) { // NOP } /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /** * The Prototype for all Generated Prototypes. * The common ancestor of all FOAM Objects. **/ var FObject = { __proto__: PropertyChangeSupport, name_: 'FObject', get Y() { return Object.prototype.hasOwnProperty.call(this, 'Y_') ? this.Y_ : ( this.Y_ = DEBUG ? this.X.sub({}, (this.X.NAME ? this.X.NAME : '') + 'Y') : this.X.sub() ); }, replaceModel_: function(model, otherModel, X) { while ( otherModel ) { // this name mangling has to use the primary model's package, otherwise // it's ambiguous which model a replacement is intended for: // ReplacementThing -> package.Thing or foo.Thing or bar.Thing... // vs foo.ReplacementThing -> foo.Thing // This means you must put your model-for-models in the same package // as the primary model-to-be-replaced. var replacementName = // want: package.otherPrimaryModel ( model.package ? model.package + '.' : '' ) + // package. ( otherModel.name ? otherModel.name : otherModel ) + // other model.name ; // PrimaryModel var replacementModel = X.lookup(replacementName); if ( replacementModel ) return replacementModel; otherModel = X.lookup(otherModel.extendsModel); } return undefined; }, create_: function() { return Object.create(this); }, create: function(args, opt_X) { // console.log('**** create ', this.model_.name, this.model_.count__ = (this.model_.count__ || 0)+1); // check for a model-for-model replacement, only if args.model is a Model instance if ( args && args.model && (opt_X || X).Model.isInstance(args.model) ) { var ret = this.replaceModel_(this.model_, args.model, opt_X || X); if ( ret ) return ret.create(args, opt_X); } // window.CREATES = (window.CREATES || {}); // var id = this.model_.id || // ((this.model_.package ? this.model_.package + '.' : '' ) + this.model_.name); // var log = window.CREATES[id] = window.CREATES[id] || { // count:0, // min: Infinity, // max: 0, // sum: 0, // all: [] // }; // log.count++; // var time = window.performance.now(); var o = this.create_(this); o.instance_ = {}; o.X = opt_X || X; if ( this.model_.instance_.imports_ && this.model_.instance_.imports_.length ) { if ( ! Object.prototype.hasOwnProperty.call(this, 'imports__') ) { this.imports__ = this.model_.instance_.imports_.map(function(e) { var s = e.split(' as '); return [s[0], s[1] || s[0]]; }); } for ( var i = 0 ; i < this.imports__.length ; i++ ) { var im = this.imports__[i]; // Don't import from Context if explicitly passed in args if ( ( ! args || ! args.hasOwnProperty(im[1]) ) && typeof o.X[im[0]] !== 'undefined' ) o[im[1]] = o.X[im[0]]; } } // if ( typeof args === 'object' ) o.copyFrom(args); if ( o.model_ ) { var agents = this.initAgents(); for ( var i = 0 ; i < agents.length ; i++ ) agents[i][1](o, o.X, args); } o.init(args); // var end = window.performance.now(); // time = end - time; // log.min = Math.min(time, log.min); // if ( time > log.max ) { // log.max = time; // log.maxObj = o; // } // log.all.push({ // name: o.name, // time: time, // obj: o, // }); // log.sum += time; // log.avg = log.sum / log.count; return o; }, init: nop, // TODO: document xbind: function(map) { var newModel = { __proto__: this, create: function(args, X) { var createArgs = {}; var key; // If args is a modelled object, just keep data from instance_. // TODO(kgr): Remove instance_ part when FObject.hasOwnProperty removed. args = args ? (args.instance_ || args) : {}; for ( key in args ) { if ( args.hasOwnProperty(key) ) createArgs[key] = args[key]; } for ( key in map ) { if ( ! createArgs.hasOwnProperty(key) ) createArgs[key] = map[key]; } return this.__proto__.create(createArgs, X); }, xbind: function(m2) { for ( var key in map ) { if ( ! m2.hasOwnProperty(key) ) m2[key] = map[key]; } return this.__proto__.xbind(m2); } }; if ( this.required__ ) newModel.required__ = aseq(this.required__, aconstant(newModel)); return newModel; }, /** Context defaults to the global namespace by default. **/ X: X, addInitAgent: function(priority, desc, agent) { agent.toString = function() { return desc; }; this.initAgents_.push([priority, agent]); }, initAgents: function() { if ( ! this.model_ ) return; // this == prototype if ( ! Object.hasOwnProperty.call(this, 'initAgents_') ) { var agents = this.initAgents_ = []; var self = this; // Four cases for export: 'this', a method, a property value$, a property Object_forEach(this.model_.instance_.exports_, function(e) { var exp = e.split('as '); if ( exp.length == 0 ) return; var key = exp[0].trim(); var alias = exp[1] || exp[0]; if ( key ) { var asValue = key !== '$' && key != '$$' && key.charAt(key.length-1) == '$'; if ( asValue ) key = key.slice(0, key.length-1); var prop = self.model_.getProperty(key); if ( prop ) { if ( asValue ) { self.addInitAgent(1, 'export property value ' + key, function(o, X) { o.Y.set(alias, o[prop.name$_]); }); } else { self.addInitAgent(1, 'export property ' + key, function(o, X) { o.Y.setValue(alias, o[prop.name$_]); }); } } else { self.addInitAgent(0, 'export other ' + key, function(o, X) { var out = typeof o[key] === "function" ? o[key].bind(o) : o[key]; o.Y.set(alias, out); }); } } else { // Exporting 'this' self.addInitAgent(0, 'export this', function(o, X) { o.Y.set(alias, o); }); } }); var fastInit = { Property: true, Method: true, /* Listener: true, Action: true, Constant: true, Message: true, Template: true, PropertyView: true, // TextFieldView: true, SimpleValue: true, DocumentationProperty: true, // Model: true, IntProperty: true, Element: true, StringProperty: true, BooleanProperty: true */ }[this.name_]; if ( fastInit ) { var keys = {}; var ps = this.model_.getRuntimeProperties(); for ( var i = 0 ; i < ps.length ; i++ ) { var prop = ps[i]; keys[prop.name] = keys[prop.name$_] = true; } this.addInitAgent(0, 'fast copy args', function fastCopyArgs(o, X, m) { if ( m.instance_ ) { m = m.instance_; for ( var key in m ) o[key] = m[key]; } else { for ( var key in m ) if ( keys[key] ) o[key] = m[key]; } }); } /*else { this.addInitAgent(0, 'fast copy args', function(o, X, m) { console.log('slowInit: ', self.name_); }); }*/ var ps = this.model_.getRuntimeProperties(); for ( var i = 0 ; i < ps.length ; i++ ) { var prop = ps[i]; if ( prop.initPropertyAgents ) { prop.initPropertyAgents(self, fastInit); } else { (function (name) { self.addInitAgent( 0, 'set proto-property ' + name, function setProtoProperty(o, X, m) { if ( m && m.hasOwnProperty(name) ) o[name] = m[name]; }); })(prop.name); } } /* this.addInitAgent(9, 'copyFrom', function(o, X, m) { if( m ) for ( var key in m ) o[key] = m[key]; }); */ // Add shortcut create() method to Models self.addInitAgent(0, 'Add create() to Model', function(o, X) { if ( Model.isInstance(o) && o.name != 'Model' ) o.create = BootstrapModel.create; }); // Works if sort is 'stable', which it isn't in Chrome // agents.sort(function(o1, o2) { return o1[0] - o2[0]; }); // TODO(kgr): make a stableSort() function in stdlib for ( var i = 0 ; i < agents.length ; i++ ) agents[i][2] = i; agents.sort(CompoundComparator( function(o1, o2) { return o1[0] - o2[0]; }, function(o1, o2) { return o1[2] - o2[2]; })); // For debugging, prints list of init agents. /* for ( var i = 0 ; i < agents.length ; i++ ) console.log(i, agents[i][0], agents[i][1].toString()); */ } return this.initAgents_; }, fromElement: function(e) { var RESERVED_ATTRS = { id: true, model: true, view: true, showactions: true, oninit: true }; var elements = this.elementMap_; // Build a map of properties keyed off of 'name' // TODO: do we have a method to lookupIC? if ( ! elements ) { elements = {}; var properties = this.model_.getRuntimeProperties(); for ( var i = 0 ; i < properties.length ; i++ ) { var p = properties[i]; if ( ! RESERVED_ATTRS[p.name] ) { elements[p.name] = p; elements[p.name.toUpperCase()] = p; } elements['p:' + p.name] = p; elements['P:' + p.name.toUpperCase()] = p; } this.elementMap_ = elements; } for ( var i = 0 ; i < e.attributes.length ; i++ ) { var attr = e.attributes[i]; var p = elements[attr.name]; var val = attr.value; if ( p ) { if ( val.startsWith('#') ) { val = val.substring(1); var $val = this.X.$(val); if ( $val ) { this[attr.name] = this.X.$(val); } else { p.fromString.call(this, val, p); } } else { // Call fromString() for attribute values because they're // String values, not Elements. p.fromString.call(this, val, p); } } else { if ( ! RESERVED_ATTRS[attr.name] ) console.warn('Unknown attribute name: "' + attr.name + '"'); } } for ( var i = 0 ; i < e.children.length ; i++ ) { var c = e.children[i]; var p = elements[c.nodeName]; if ( p ) { p.fromElement.call(this, c, p); } else { console.warn('Unknown element name: "' + c.nodeName + '"'); } } return this; }, createFOAMGetter: function(name, getter) { var stack = Events.onGet.stack; return function FOAMGetter() { var value = getter.call(this, name); var f = stack[0]; f && f(this, name, value); return value; }; }, createFOAMSetter: function(name, setter) { var stack = Events.onSet.stack; return function FOAMSetter(newValue) { var f = stack[0]; if ( f && ! f(this, name, newValue) ) return; setter.call(this, newValue, name); }; }, toString: function() { // TODO: do something to detect loops which cause infinite recurrsions. // console.log(this.model_.name + "Prototype"); return this.model_.name + "Prototype"; // return this.toJSON(); }, hasOwnProperty: function(name) { return typeof this.instance_[name] !== 'undefined'; // return this.instance_.hasOwnProperty(name); }, writeActions: function(other, out) { var properties = this.model_.getRuntimeProperties(); for ( var i = 0, property ; property = properties[i] ; i++ ) { if ( property.actionFactory ) { var actions = property.actionFactory(this, property.f(this), property.f(other)); for (var j = 0; j < actions.length; j++) out(actions[j]); } } }, equals: function(other) { return this.compareTo(other) == 0; }, compareTo: function(other) { if ( other === this ) return 0; if ( this.model_ !== other.model_ ) { // TODO: This provides unstable ordering if two objects have a different model_ // but they have the same id. return this.model_.id.compareTo(other.model_ && other.model_.id) || 1; } var ps = this.model_.getRuntimeProperties(); for ( var i = 0 ; i < ps.length ; i++ ) { var r = ps[i].compare(this, other); if ( r ) return r; } return 0; }, diff: function(other) { var diff = {}; var properties = this.model_.getRuntimeProperties(); for ( var i = 0, property ; property = properties[i] ; i++ ) { if ( Array.isArray(property.f(this)) ) { var subdiff = property.f(this).diff(property.f(other)); if ( subdiff.added.length !== 0 || subdiff.removed.length !== 0 ) { diff[property.name] = subdiff; } continue; } if ( property.f(this).compareTo(property.f(other)) !== 0) { diff[property.name] = property.f(other); } } return diff; }, /** Reset a property to its default value. **/ clearProperty: function(name) { delete this.instance_[name]; }, defineProperty: function(prop) { var name = prop.name; prop.name$_ = name + '$'; // Add a 'name$' psedo-property if not already defined // Faster to define on __ROOT__, but not as good for auto-completion var obj = DEBUG ? this : __ROOT__; if ( ! obj.__lookupGetter__(prop.name$_) ) { Object.defineProperty(obj, prop.name$_, { get: function getValue() { return this.propertyValue(name); }, set: function setValue(value) { Events.link(value, this.propertyValue(name)); }, configurable: true }); } var pgetter, psetter; if ( prop.getter ) { pgetter = this.createFOAMGetter(name, prop.getter); } else { if ( prop.lazyFactory || prop.factory ) { var f = prop.lazyFactory || prop.factory; getter = function factory() { if ( typeof this.instance_[name] === 'undefined' ) { this.instance_[name] = null; // prevents infinite recursion // console.log('Ahead of order factory: ', prop.name); //debugger; var val = f.call(this, prop); if ( typeof val === 'undefined' ) val = null; this[name] = val; } return this.instance_[name]; }; } else if ( prop.defaultValueFn ) { var f = prop.defaultValueFn; getter = function defaultValueFn() { return typeof this.instance_[name] !== 'undefined' ? this.instance_[name] : f.call(this, prop); }; } else { var defaultValue = prop.defaultValue; getter = function getInstanceVar() { return typeof this.instance_[name] !== 'undefined' ? this.instance_[name] : defaultValue; }; } pgetter = this.createFOAMGetter(name, getter); } if ( prop.setter ) { psetter = this.createFOAMSetter(name, prop.setter); } else { var setter = function setInstanceValue(oldValue, newValue) { this.instance_[name] = newValue; }; if ( prop.type === 'int' || prop.type === 'float' ) { setter = (function(setter) { return function numberSetter(oldValue, newValue) { setter.call(this, oldValue, typeof newValue !== 'number' ? Number(newValue) : newValue); }; })(setter); } if ( prop.onDAOUpdate ) { if ( typeof prop.onDAOUpdate === 'string' ) { setter = (function(setter, onDAOUpdate, listenerName) { return function onDAOUpdateSetter(oldValue, newValue) { setter.call(this, oldValue, newValue); var listener = this[listenerName] || ( this[listenerName] = this[onDAOUpdate].bind(this) ); if ( oldValue ) oldValue.unlisten(listener); if ( newValue ) { newValue.listen(listener); listener(); } }; })(setter, prop.onDAOUpdate, prop.name + '_onDAOUpdate'); } else { setter = (function(setter, onDAOUpdate, listenerName) { return function onDAOUpdateSetter2(oldValue, newValue) { setter.call(this, oldValue, newValue); var listener = this[listenerName] || ( this[listenerName] = onDAOUpdate.bind(this) ); if ( oldValue ) oldValue.unlisten(listener); if ( newValue ) { newValue.listen(listener); listener(); } }; })(setter, prop.onDAOUpdate, prop.name + '_onDAOUpdate'); } } if ( prop.postSet ) { setter = (function(setter, postSet) { return function postSetSetter(oldValue, newValue) { setter.call(this, oldValue, newValue); postSet.call(this, oldValue, newValue, prop) }; })(setter, prop.postSet); } var propertyTopic = PropertyChangeSupport.propertyTopic(name); setter = (function(setter) { return function propertyChangeSetter(oldValue, newValue) { setter.call(this, oldValue, newValue); this.propertyChange_(propertyTopic, oldValue, newValue); }; })(setter); if ( prop.preSet ) { setter = (function(setter, preSet) { return function preSetSetter(oldValue, newValue) { setter.call(this, oldValue, preSet.call(this, oldValue, newValue, prop)); }; })(setter, prop.preSet); } if ( prop.adapt ) { setter = (function(setter, adapt) { return function adaptSetter(oldValue, newValue) { setter.call(this, oldValue, adapt.call(this, oldValue, newValue, prop)); }; })(setter, prop.adapt); } setter = (function(setter, defaultValue) { return function setInstanceVar(newValue) { setter.call(this, typeof this.instance_[name] === 'undefined' ? defaultValue : this.instance_[name], newValue); }; })(setter, prop.defaultValue); psetter = this.createFOAMSetter(name, setter); } Object.defineProperty(this, name, { get: pgetter, set: psetter, configurable: true }); // Let the property install other features into the Prototype prop.install && prop.install.call(this, prop); }, addMethod: function(name, method) { if ( this.__proto__[name] ) { override(this, name, method); } else { this[name] = method; } }, hashCode: function() { var hash = 17; var properties = this.model_.getRuntimeProperties(); for ( var i = 0 ; i < properties.length ; i++ ) { var prop = this[properties[i].name]; var code = ! prop ? 0 : prop.hashCode ? prop.hashCode() : prop.toString().hashCode(); hash = ((hash << 5) - hash) + code; hash &= hash; } return hash; }, // TODO: this should be monkey-patched from a 'ProtoBuf' library toProtobuf: function() { var out = ProtoWriter.create(); this.outProtobuf(out); return out.value; }, // TODO: this should be monkey-patched from a 'ProtoBuf' library outProtobuf: function(out) { var proprties = this.model_getRuntimeProperties(); for ( var i = 0 ; i < properties.length ; i++ ) { var prop = properties[i]; if ( Number.isFinite(prop.prototag) ) prop.outProtobuf(this, out); } }, /** Create a shallow copy of this object. **/ clone: function() { var c = Object.create(this.__proto__); c.instance_ = {}; c.X = this.X; for ( var key in this.instance_ ) { var value = this[key]; if ( value ) { var prop = this.model_.getProperty(key); if ( prop && prop.cloneProperty ) c.instance_[key] = prop.cloneProperty.call(prop, value); } } return c; }, /** Create a deep copy of this object. **/ deepClone: function() { var c = Object.create(this.__proto__); c.instance_ = {}; c.X = this.X; for ( var key in this.instance_ ) { var value = this[key]; if ( value ) { var prop = this.model_.getProperty(key); if ( prop && prop.deepCloneProperty ) c.instance_[key] = prop.deepCloneProperty.call(prop, value); } } return c; }, /** @return this **/ copyFrom: function(src) { /* // TODO: remove the 'this.model_' check when all classes modelled if ( src && this.model_ ) { for ( var i = 0 ; i < this.model_.properties.length ; i++ ) { var prop = this.model_.properties[i]; // If the src is modelled, and it has an instance_ // BUT the instance doesn't have a value for the property, // then don't copy this value over since it's a default value. if ( src.model_ && src.instance_ && !src.instance_.hasOwnProperty(prop.name) ) continue; if ( prop.name in src ) this[prop.name] = src[prop.name]; } } */ if ( src && this.model_ ) { var ps = this.model_.getRuntimeProperties(); for ( var i = 0 ; i < ps.length ; i++ ) { var prop = ps[i]; if ( src.hasOwnProperty(prop.name) ) this[prop.name] = src[prop.name]; if ( src.hasOwnProperty(prop.name$_) ) this[prop.name$_] = src[prop.name$_]; } } return this; }, output: function(out) { return JSONUtil.output(out, this); }, toJSON: function() { return JSONUtil.stringify(this); }, toXML: function() { return XMLUtil.stringify(this); }, write: function(document, opt_view) { //console.warn("FObject.write() for ", this.model_.id," is not safe when called from async code."); var view = (opt_view || X.foam.ui.DetailView).create({ model: this.model_, data: this, showActions: true }); view.write(document); }, defaultView: function(opt_view) { return (opt_view || X.foam.ui.DetailView).create({ model: this.model_, data: this, showActions: true }); }, decorate: function(name, func, that) { var delegate = this[name]; this[name] = function() { return func.call(this, that, delegate.bind(this), arguments); }; return this; }, addDecorator: function(decorator) { if ( decorator.decorateObject ) decorator.decorateObject(this); for ( var i = 0 ; i < decorator.model_.methods.length ; i++ ) { var method = decorator.model_.methods[i]; if ( method.name !== 'decorateObject' ) this.decorate(method.name, method.code, decorator); } return this; } }; /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /** * Prototype for original proto-Models. * Used during bootstrapping to create the real Model * and PropertyModel. * * TODO: The handling of the various property types (properties, * templates, listeners, etc.) shouldn't be handled here because * it isn't extensible. The handling should be defined in the * properties property (so meta). * * TODO: Is still used by a few views in view.js. Those views * should be fixed and then BootstrapModel should be deleted at * the end of metamodel.js once the real Model is created. **/ function defineLocalProperty(cls, name, factory) { Object.defineProperty(cls, name, { get: function() { console.assert(this !== cls, 'Called property getter from prototype: ' + name); var value = factory.call(this); Object.defineProperty(this, name, { configurable: true, value: value }); return value; }, configurable: true }); } this.Constant = null; this.Method = null; this.Action = null; this.Relationship = null; /** * Override a method, making calling the overridden method possible by * calling this.SUPER(); **/ function override(cls, methodName, method) { var super_ = cls[methodName]; var SUPER = function() { return super_.apply(this, arguments); }; var slowF = function(OLD_SUPER, args) { try { return method.apply(this, args); } finally { this.SUPER = OLD_SUPER; } }; var f = function() { var OLD_SUPER = this.SUPER; this.SUPER = SUPER; if ( OLD_SUPER ) return slowF.call(this, OLD_SUPER, arguments); // Fast-Path when it doesn't matter if we restore SUPER or not var ret = method.apply(this, arguments); this.SUPER = null; return ret; }; f.toString = function() { return method.toString(); }; f.super_ = super_; cls[methodName] = f; } var BootstrapModel = { __proto__: PropertyChangeSupport, name_: 'BootstrapModel <startup only, error if you see this>', addTraitToModel_: function(traitModel, parentModel) { var parentName = parentModel && parentModel.id ? parentModel.id.replace(/\./g, '__') : ''; var traitName = traitModel.id ? traitModel.id.replace(/\./g, '__') : ''; var name = parentName + '_ExtendedWith_' + traitName; if ( ! lookup(name) ) { var model = traitModel.clone(); model.package = ''; model.name = name; model.extendsModel = parentModel && parentModel.id; model.models = traitModel.models; // unclone sub-models, we don't want multiple copies of them floating around GLOBAL.X.registerModel(model); } var ret = GLOBAL.X.lookup(name); console.assert(ret, 'Error adding Trait to Model, unknown name: ', name); return ret; }, buildProtoImports_: function(props) { // build imports as psedo-properties Object_forEach(this.instance_.imports_, function(i) { var imp = i.split(' as '); var key = imp[0]; var alias = imp[1] || imp[0]; if ( alias.length && alias.charAt(alias.length-1) == '$' ) alias = alias.slice(0, alias.length-1); if ( ! this.getProperty(alias) ) { var prop = Property.create({ name: alias, transient: true, hidden: true }); // Prevent imports from being cloned. prop.cloneProperty = prop.deepCloneProperty = null; props.push(prop); } }.bind(this)); }, buildProtoProperties_: function(cls, extendsModel, props) { // build properties for ( var i = 0 ; i < props.length ; i++ ) { var p = props[i]; if ( extendsModel ) { var superProp = extendsModel.getProperty(p.name); if ( superProp ) { var p0 = p; p = superProp.clone().copyFrom(p); // A more elegant way to do this would be to have a ModelProperty // which has a ModelPropertyProperty called 'reduceWithSuper'. if ( p0.adapt && superProp.adapt ) { // console.log('(DEBUG) sub adapt: ', this.name + '.' + p.name); p.adapt = (function(a1, a2) { return function(oldValue, newValue, prop) { return a2.call(this, oldValue, a1.call(this, oldValue, newValue, prop), prop); };})(p0.adapt, superProp.adapt); } if ( p0.preSet && superProp.preSet ) { // console.log('(DEBUG) sub preSet: ', this.name + '.' + p.name); p.preSet = (function(a1, a2) { return function(oldValue, newValue, prop) { return a2.call(this, oldValue, a1.call(this, oldValue, newValue, prop), prop); };})(p0.preSet, superProp.preSet); } if ( p0.postSet && superProp.postSet ) { // console.log('(DEBUG) sub postSet: ', this.name + '.' + p.name); p.postSet = (function(a1, a2) { return function(oldValue, newValue, prop) { a2.call(this, oldValue, newValue, prop); a1.call(this, oldValue, newValue, prop); };})(p0.postSet, superProp.postSet); } props[i] = p; this[constantize(p.name)] = p; } } cls.defineProperty(p); } this.propertyMap_ = null; }, buildProtoMethods_: function(cls) { // add methods for ( key in this.methods ) { var m = this.methods[key]; if ( Method && Method.isInstance(m) ) { cls.addMethod(m.name, m.generateFunction()); } else { cls.addMethod(key, m); } } }, buildPrototype: function() { /* Internal use only. */ // save our pure state // Note: Only documentation browser uses this, and it will be replaced // by the new Feature Oriented bootstrapping process, so only use the // extra memory in DEBUG mode. if ( DEBUG ) BootstrapModel.saveDefinition(this); if ( this.extendsModel && ! this.X.lookup(this.extendsModel) ) throw 'Unknown Model in extendsModel: ' + this.extendsModel; var extendsModel = this.extendsModel && this.X.lookup(this.extendsModel); if ( this.traits ) for ( var i = 0 ; i < this.traits.length ; i++ ) { var trait = this.traits[i]; var traitModel = this.X.lookup(trait); console.assert(traitModel, 'Unknown trait: ' + trait); if ( traitModel ) { extendsModel = this.addTraitToModel_(traitModel, extendsModel); } else { console.warn('Missing trait: ', trait, ', in Model: ', this.name); } } var proto = extendsModel ? extendsModel.getPrototype() : FObject; var cls = Object.create(proto); cls.model_ = this; cls.name_ = this.name; // Install a custom constructor so that Objects are named properly // in the JS memory profiler. // Doesn't work for Model because of some Bootstrap ordering issues. /* if ( this.name && this.name !== 'Model' && ! ( window.chrome && chrome.runtime && chrome.runtime.id ) ) { var s = '(function() { var XXX = function() { }; XXX.prototype = this; return function() { return new XXX(); }; })'.replace(/XXX/g, this.name); try { cls.create_ = eval(s).call(cls); } catch (e) { } }*/ // add sub-models // this.models && this.models.forEach(function(m) { // cls[m.name] = JSONUtil.mapToObj(m); // }); // Workaround for crbug.com/258552 this.models && Object_forEach(this.models, function(m) { //cls.model_[m.name] = cls[m.name] = JSONUtil.mapToObj(X, m, Model); if ( this[m.name] ) cls[m.name] = this[m.name]; }.bind(this)); // TODO(adamvy): This shouldn't be required, commenting out for now. // if ( extendsModel ) this.requires = this.requires.concat(extendsModel.requires); // build requires Object_forEach(this.requires, function(i) { var imp = i.split(' as '); var m = imp[0]; var path = m.split('.'); var key = imp[1] || path[path.length-1]; defineLocalProperty(cls, key, function() { var Y = this.Y; var model = this.X.lookup(m); console.assert(model, 'Unknown Model: ' + m + ' in ' + this.name_); return { __proto__: model, create: function(args, X) { return model.create(args, X || Y); } }; }); }); var props = this.instance_.properties_ = this.properties ? this.properties.clone() : []; this.instance_.imports_ = this.imports; if ( extendsModel ) this.instance_.imports_ = this.instance_.imports_.concat(extendsModel.instance_.imports_); this.buildProtoImports_(props); this.buildProtoProperties_(cls, extendsModel, props); // Copy parent Model's Property and Relationship Contants to this Model. if ( extendsModel ) { for ( var i = 0 ; i < extendsModel.instance_.properties_.length ; i++ ) { var p = extendsModel.instance_.properties_[i]; var name = constantize(p.name); if ( ! this[name] ) this[name] = p; } for ( i = 0 ; i < extendsModel.relationships.length ; i++ ) { var r = extendsModel.relationships[i]; var name = constantize(r.name); if ( ! this[name] ) this[name] = r; } } // Handle 'exports' this.instance_.exports_ = this.exports ? this.exports.clone() : []; if ( extendsModel ) this.instance_.exports_ = this.instance_.exports_.concat(extendsModel.instance_.exports_); // templates this.templates && Object_forEach(this.templates, function(t) { cls.addMethod(t.name, t.code ? t.code : TemplateUtil.lazyCompile(t)); }); // add actions this.instance_.actions_ = this.actions ? this.actions.clone() : []; if ( this.actions ) { for ( var i = 0 ; i < this.actions.length ; i++ ) { (function(a) { if ( extendsModel ) { var superAction = extendsModel.getAction(a.name); if ( superAction ) { a = superAction.clone().copyFrom(a); } } this.instance_.actions_[i] = a; if ( ! Object.prototype.hasOwnProperty.call(cls, constantize(a.name)) ) cls[constantize(a.name)] = a; cls.addMethod(a.name, function(opt_x) { a.maybeCall(opt_x || this.X, this); }); }.bind(this))(this.actions[i]); } } var key; // add constants if ( this.constants ) { for ( var i = 0 ; i < this.constants.length ; i++ ) { var c = this.constants[i]; cls[c.name] = this[c.name] = c.value; } } // add messages if ( this.messages && this.messages.length > 0 && Message ) { Object_forEach(this.messages, function(m, key) { if ( ! Message.isInstance(m) ) { m = this.messages[key] = Message.create(m); } var clsProps = {}, mdlProps = {}, constName = constantize(m.name); clsProps[m.name] = { get: function() { return m.value; } }; clsProps[constName] = { value: m }; mdlProps[constName] = { value: m }; Object.defineProperties(cls, clsProps); Object.defineProperties(this, mdlProps); }.bind(this)); } this.buildProtoMethods_(cls); var self = this; // add relationships this.relationships && this.relationships.forEach(function(r) { // console.log('************** rel: ', r, r.name, r.label, r.relatedModel, r.relatedProperty); var name = constantize(r.name); if ( ! self[name] ) self[name] = r; defineLazyProperty(cls, r.name, function() { var m = this.X.lookup(r.relatedModel); var lcName = m.name[0].toLowerCase() + m.name.substring(1); var dao = this.X[lcName + 'DAO'] || this.X[m.name + 'DAO'] || this.X[m.plural]; if ( ! dao ) { console.error('Relationship ' + r.name + ' needs ' + (m.name + 'DAO') + ' or ' + m.plural + ' in the context, and neither was found.'); } dao = RelationshipDAO.create({ delegate: dao, relatedProperty: m.getProperty(r.relatedProperty), relativeID: this.id }); return { get: function() { return dao; }, configurable: true }; }); }); // TODO: move this somewhere better var createListenerTrampoline = function(cls, name, fn, isMerged, isFramed, whenIdle) { // bind a trampoline to the function which // re-binds a bound version of the function // when first called console.assert( fn, 'createListenerTrampoline: fn not defined'); fn.name = name; Object.defineProperty(cls, name, { get: function () { var l = fn.bind(this); /* if ( ( isFramed || isMerged ) && this.X.isBackground ) { console.log('*********************** ', this.model_.name); } */ if ( whenIdle ) l = Movement.whenIdle(l); if ( isFramed ) { l = EventService.framed(l, this.X); } else if ( isMerged ) { l = EventService.merged( l, (isMerged === true) ? undefined : isMerged, this.X); } Object.defineProperty(this, name, { configurable: true, value: l }); return l; }, configurable: true }); }; // add listeners if ( Array.isArray(this.listeners) ) { for ( var i = 0 ; i < this.listeners.length ; i++ ) { var l = this.listeners[i]; createListenerTrampoline(cls, l.name, l.code, l.isMerged, l.isFramed, l.whenIdle); } } else if ( this.listeners ) { // this.listeners.forEach(function(l, key) { // Workaround for crbug.com/258522 Object_forEach(this.listeners, function(l, key) { createListenerTrampoline(cls, key, l); }); } // add topics // this.topics && this.topics.forEach(function(t) { // Workaround for crbug.com/258522 this.topics && Object_forEach(this.topics, function(t) { // TODO: something }); // copy parent model's properties and actions into this model if ( extendsModel ) { this.getProperty(''); var ips = []; // inherited properties var ps = extendsModel.instance_.properties_; for ( var i = 0 ; i < ps.length ; i++ ) { var p = ps[i]; if ( ! this.getProperty(p.name) ) { ips.push(p); this.propertyMap_[p.name] = p; } } if ( ips.length ) { this.instance_.properties_ = ips.concat(this.instance_.properties_); } var ias = []; var as = extendsModel.instance_.actions_; for ( var i = 0 ; i < as.length ; i++ ) { var a = as[i]; if ( ! ( this.getAction && this.getAction(a.name) ) ) ias.push(a); } if ( ias.length ) { this.instance_.actions_ = ias.concat(this.instance_.actions_); } } // build primary key getter and setter if ( this.instance_.properties_.length > 0 && ! cls.__lookupGetter__('id') ) { var primaryKey = this.ids; if ( primaryKey.length == 1 ) { cls.__defineGetter__('id', function() { return this[primaryKey[0]]; }); cls.__defineSetter__('id', function(val) { this[primaryKey[0]] = val; }); } else if (primaryKey.length > 1) { cls.__defineGetter__('id', function() { return primaryKey.map(function(key) { return this[key]; }.bind(this)); }); cls.__defineSetter__('id', function(val) { primaryKey.map(function(key, i) { this[key] = val[i]; }.bind(this)); }); } } return cls; }, // ???(kgr): Who uses this? If it's the build tool, then better putting it there. getAllRequires: function() { var requires = {}; this.requires.forEach(function(r) { requires[r.split(' ')[0]] = true; }); this.traits.forEach(function(t) { requires[t] = true; }); if ( this.extendsModel ) requires[this.extendsModel] = true; function setModel(o) { if ( o && o.model_ ) requires[o.model_.id] = true; } this.properties.forEach(setModel); this.actions.forEach(setModel); this.templates.forEach(setModel); this.listeners.forEach(setModel); return Object.keys(requires); }, getPrototype: function() { /* Returns the definition $$DOC{ref:'Model'} of this instance. */ if ( ! this.instance_.prototype_ ) { //console.profile('getPrototype' + this.name); //for ( var i = 0 ; i < 0 ; i++ ) this.buildPrototype(); //console.profileEnd(); return this.instance_.prototype_ = this.buildPrototype(); } return this.instance_.prototype_; // return this.instance_.prototype_ || ( this.instance_.prototype_ = this.buildPrototype() ); }, saveDefinition: function(self) { self.definition_ = {}; // TODO: introspect Model, copy the other non-array properties of Model // DocumentationBootstrap's getter gets called here, which causes a .create() and an infinite loop // Model.properties.forEach(function(prop) { // var propVal = self[prop.name]; // if (propVal) { // if (Array.isArray(propVal)) { // // force array copy, so we don't share changes made later // self.definition_[prop.name] = [].concat(propVal); // } else { // self.definition_[prop.name] = propVal; // } // } // }.bind(self)); // TODO: remove these once the above loop works // clone feature lists to avoid sharing the reference in the copy and original if (Array.isArray(self.methods)) self.definition_.methods = [].concat(self.methods); if (Array.isArray(self.templates)) self.definition_.templates = [].concat(self.templates); if (Array.isArray(self.relationships)) self.definition_.relationships = [].concat(self.relationships); if (Array.isArray(self.properties)) self.definition_.properties = [].concat(self.properties); if (Array.isArray(self.actions)) self.definition_.actions = [].concat(self.actions); if (Array.isArray(self.listeners)) self.definition_.listeners = [].concat(self.listeners); if (Array.isArray(self.models)) self.definition_.models = [].concat(self.models); if (Array.isArray(self.tests)) self.definition_.tests = [].concat(self.tests); if (Array.isArray(self.issues)) self.definition_.issues = [].concat(self.issues); self.definition_.__proto__ = FObject; }, create: function(args, opt_X) { return this.getPrototype().create(args, opt_X); }, isSubModel: function(model) { /* Returns true if the given instance extends this $$DOC{ref:'Model'} or a descendant of this. */ if ( ! model || ! model.getPrototype ) return false; var subModels_ = this.subModels_ || ( this.subModels_ = {} ); if ( ! subModels_.hasOwnProperty(model.id) ) { subModels_[model.id] = ( model.getPrototype() === this.getPrototype() || this.isSubModel(model.getPrototype().__proto__.model_) ); } return subModels_[model.id]; }, getRuntimeProperties: function() { if ( ! this.instance_.properties_ ) this.getPrototype(); return this.instance_.properties_; }, getProperty: function(name) { /* Returns the requested $$DOC{ref:'Property'} of this instance. */ // NOTE: propertyMap_ is invalidated in a few places // when properties[] is updated. if ( ! this.propertyMap_ ) { var m = this.propertyMap_ = {}; var properties = this.getRuntimeProperties(); for ( var i = 0 ; i < properties.length ; i++ ) { var prop = properties[i]; m[prop.name] = prop; } this.propertyMap_ = m; } return this.propertyMap_[name]; }, getAction: function(name) { /* Returns the requested $$DOC{ref:'Action'} of this instance. */ for ( var i = 0 ; i < this.instance_.actions_.length ; i++ ) if ( this.instance_.actions_[i].name === name ) return this.instance_.actions_[i]; }, hashCode: function() { var string = ''; var properties = this.getRuntimeProperties(); for ( var key in properties ) { string += properties[key].toString(); } return string.hashCode(); }, isInstance: function(obj) { /* Returns true if the given instance extends this $$DOC{ref:'Model'}. */ return obj && obj.model_ && this.isSubModel(obj.model_); }, toString: function() { return "BootstrapModel(" + this.name + ")"; }, arequire: function() { if ( this.required__ ) return this.required__; var future = afuture(); this.required__ = future.get; var go = function() { var args = []; if ( this.extendsModel ) args.push(arequire(this.extendsModel, this.X)); var i; if ( this.traits ) { for ( i = 0; i < this.traits.length; i++ ) { args.push(arequire(this.traits[i], this.X)); } } var model = this; if ( this.templates ) for ( i = 0 ; i < this.templates.length ; i++ ) { var t = this.templates[i]; args.push( aif(!t.code, aseq( aevalTemplate(this.templates[i], this), (function(t) { return function(ret, m) { t.code = m; ret(); };})(t)))); } if ( args.length ) args = [aseq.apply(null, args)]; if ( this.requires ) { for ( var i = 0 ; i < this.requires.length ; i++ ) { var r = this.requires[i]; var m = r.split(' as '); if ( m[0] == this.id ) { console.warn("Model requires itself: " + this.id); } else { args.push(arequire(m[0], this.X)); } } } args.push(function(ret) { if ( this.X.i18nModel ) this.X.i18nModel(ret, this, this.X); else ret(); }.bind(this)); aseq.apply(null, args)(function() { this.finished__ = true; future.set(this); }.bind(this)); }.bind(this); if ( this.extra__ ) this.extra__(go); else go(); return this.required__ }, getMyFeature: function(featureName) { /* Returns the feature with the given name from the runtime object (the features available to an instance of the model). */ if ( ! Object.prototype.hasOwnProperty.call(this, 'featureMap_') ) { var map = this.featureMap_ = {}; function add(a) { if ( ! a ) return; for ( var i = 0 ; i < a.length ; i++ ) { var f = a[i]; map[f.name.toUpperCase()] = f; } } add(this.getRuntimeProperties()); add(this.instance_.actions_); add(this.methods); add(this.listeners); add(this.templates); add(this.models); add(this.tests); add(this.relationships); add(this.issues); } return this.featureMap_[featureName.toUpperCase()]; }, getRawFeature: function(featureName) { /* Returns the raw (not runtime, not inherited, non-buildPrototype'd) feature from the model definition. */ if ( ! Object.prototype.hasOwnProperty.call(this, 'rawFeatureMap_') ) { var map = this.featureMap_ = {}; function add(a) { if ( ! a ) return; for ( var i = 0 ; i < a.length ; i++ ) { var f = a[i]; map[f.name.toUpperCase()] = f; } } add(this.properties); add(this.actions); add(this.methods); add(this.listeners); add(this.templates); add(this.models); add(this.tests); add(this.relationships); add(this.issues); } return this.featureMap_[featureName.toUpperCase()]; }, getAllMyRawFeatures: function() { /* Returns the raw (not runtime, not inherited, non-buildPrototype'd) list of features from the model definition. */ var featureList = []; var arrayOrEmpty = function(arr) { return ( arr && Array.isArray(arr) ) ? arr : []; }; [ arrayOrEmpty(this.properties), arrayOrEmpty(this.actions), arrayOrEmpty(this.methods), arrayOrEmpty(this.listeners), arrayOrEmpty(this.templates), arrayOrEmpty(this.models), arrayOrEmpty(this.tests), arrayOrEmpty(this.relationships), arrayOrEmpty(this.issues) ].map(function(list) { featureList = featureList.concat(list); }); return featureList; }, getFeature: function(featureName) { /* Returns the feature with the given name, including inherited features. */ var feature = this.getMyFeature(featureName); if ( ! feature && this.extendsModel ) { var ext = this.X.lookup(this.extendsModel); if ( ext ) return ext.getFeature(featureName); } else { return feature; } }, // getAllFeatures accounts for inheritance through extendsModel getAllRawFeatures: function() { var featureList = this.getAllMyRawFeatures(); if ( this.extendsModel ) { var ext = this.X.lookup(this.extendsModel); if ( ext ) { ext.getAllFeatures().map(function(subFeat) { var subName = subFeat.name.toUpperCase(); if ( ! featureList.mapFind(function(myFeat) { // merge in features we don't already have return myFeat && myFeat.name && myFeat.name.toUpperCase() === subName; }) ) { featureList.push(subFeat); } }); } } return featureList; }, atest: function() { var seq = []; var allPassed = true; for ( var i = 0 ; i < this.tests.length ; i++ ) { seq.push( (function(test, model) { return function(ret) { test.atest(model)(function(passed) { if ( ! passed ) allPassed = false; ret(); }) }; })(this.tests[i], this)); } seq.push(function(ret) { ret(allPassed); }); return aseq.apply(null, seq); } }; /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ var BinaryProtoGrammar; var DocumentationBootstrap = { name: 'documentation', type: 'Documentation', view: function() { return X.foam.ui.DetailView.create({model: Documentation}); }, help: 'Documentation associated with this entity.', documentation: "The developer documentation for this $$DOC{ref:'.'}. Use a $$DOC{ref:'DocModelView'} to view documentation.", setter: function(nu) { if ( ! DEBUG ) return; this.instance_.documentation = nu; }, getter: function() { if ( ! DEBUG ) return ''; var doc = this.instance_.documentation; if ( doc && typeof Documentation != "undefined" && Documentation // a source has to exist (otherwise we'll return undefined below) && ( ! doc.model_ // but we don't know if the user set model_ || ! doc.model_.getPrototype // model_ could be a string || ! Documentation.isInstance(doc) // check for correct type ) ) { // So in this case we have something in documentation, but it's not of the // "Documentation" model type, so FOAMalize it. if ( doc.body ) { this.instance_.documentation = Documentation.create( doc ); } else { this.instance_.documentation = Documentation.create({ body: doc }); } } // otherwise return the previously FOAMalized model or undefined if nothing specified. //console.log("getting ", this.instance_.documentation) return this.instance_.documentation; } } var Model = { __proto__: BootstrapModel, instance_: {}, name: 'Model', plural:'Models', help: "Describes the attributes and properties of an entity.", documentation: { body: function() { /* <p>In FOAM, $$DOC{ref:'Model'} is the basic unit for describing data and behavior. $$DOC{ref:'Model'} itself is a $$DOC{ref:'Model'}, since it defines what can be defined, but also defines itself. See $$DOC{ref:'developerDocs.Welcome.chapters.modelsAtRuntime', text: 'Models in Action'} for more details.</p> <p>To create an instance of a $$DOC{ref:'Model'}, add it in your $$DOC{ref:'Model.requires'} list, then, in Javascript:</p> <p> <code>this.YourModel.create({ propName: val... })</code> creates an instance. </p> <p> Under the covers, $$DOC{ref:'Model.requires'} is creating an alias for the $$DOC{ref:'Model'} instance that exists in your context. You can access it directly at <code>this.X.yourPackage.YourModel</code>.</p> <p>Note: <ul> <li>The definition of your model is a $$DOC{ref:'Model'} instance (with YourModel.model_ === Model), while instances of your model have your new type (myInstance.model_ === YourModel). This differs from other object-oriented systems where the definition of a class and instances of the class are completely separate entities. In FOAM every class definition is an instance of $$DOC{ref:'Model'}, including itself.</li> <li>$$DOC{ref:'Model.exports',text:'Exporting'} a model property allows seamless dependency injection. See the $$DOC{ref:'developerDocs.Context', text:'Context documentation'} for more information.</li> <li>Calling .create direclty on a $$DOC{ref:'Model'} from your context, without using the $$DOC{ref:'.requires'} shortcut, must include the context: <code>this.X.MyModel.create({args}, this.X);</code>. Use $$DOC{ref:'.requires'} unless you have some compelling reason not to!</li> </ul> </p> <p>For more information about how $$DOC{ref:'Model',usePlural:true} are instantiated, see $$DOC{ref:'developerDocs.Welcome.chapters.modelsAtRuntime',text:'Welcome to Models at Runtime'}. */ } }, tableProperties: [ 'package', 'name', 'label', 'plural' ], properties: [ { name: 'id', hidden: true, transient: true }, { name: 'sourcePath', help: 'Source location of this Model.', defaultValue: '', mode: 'read-only', transient: true }, { name: 'abstract', type: 'boolean', defaultValue: false, help: 'If the java class is abstract.', documentation: function() { /* When running FOAM in a Java environment, specifies whether the Java class built from this $$DOC{ref:'Model'} should be declared abstract.*/} }, { name: 'package', help: 'Package that this Model belongs to.', defaultValue: '', postSet: function(_, p) { return this.id = p ? p + '.' + this.name : this.name; }, documentation: function() { /* <p>The package (or namespace) in which the $$DOC{ref:'.'} belongs. The dot-separated package name is prepended to the $$DOC{ref:'.'} name.</p> <p>For example: </p> <p><code>MODEL ({ name: 'Train', package: 'com.company.modules' });<br/> ...<br/> // when creating an instance of the model (your $$DOC{ref:'developerDocs.Context', text:'context'} is this.X):<br/> this.X.com.company.modules.Train.create();<br/> </code></p> <p>Use $$DOC{ref:'Model.imports'} to avoid typing the package name repeatedly.</p> <p>When running FOAM in a Java environment, specifies the package in which to declare the Java class built from this $$DOC{ref:'Model'}. </p> */} }, { name: 'name', type: 'String', postSet: function(_, n) { return this.id = this.package ? this.package + '.' + n : n; }, required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', help: 'The coding identifier for the entity.', documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}. $$DOC{ref:'Model.name'} should generally only contain identifier-safe characters. $$DOC{ref:'Model'} definition names should use CamelCase starting with a capital letter, while $$DOC{ref:'Property',usePlural:true}, $$DOC{ref:'Method',usePlural:true}, and other features defined inside a $$DOC{ref:'Model'} should use camelCase staring with a lower case letter. */} }, { name: 'label', type: 'String', displayWidth: 70, displayHeight: 1, defaultValueFn: function() { return labelize(this.name); }, help: 'The display label for the entity.', documentation: function() { /* A human readable label for the $$DOC{ref:'Model'}. May contain spaces or other odd characters. */} }, { name: 'javaClassName', type: 'String', displayWidth: 70, displayHeight: 1, defaultValueFn: function() { return (this.abstract ? 'Abstract' : '') + this.name; }, help: 'The Java classname of this Model.', documentation: function() { /* When running FOAM in a Java environment, specifies the name of the Java class to be built from this $$DOC{ref:'Model'}.*/} }, { name: 'extendsModel', label: 'Extends', type: 'String', displayWidth: 70, displayHeight: 1, defaultValue: '', help: 'The parent model of this model.', documentation: function() { /* <p>Specifies the $$DOC{ref:'Model.name'} of the $$DOC{ref:'Model'} that this model should inherit from. Like object-oriented inheritance, this $$DOC{ref:'Model'} will gain the $$DOC{ref:'Property',usePlural:true}, $$DOC{ref:'Method',usePlural:true}, and other features defined inside the $$DOC{ref:'Model'} you extend.</p> <p>You may override features by redefining them in your $$DOC{ref:'Model'}.</p> <p>Like most inheritance schemes, instances of your $$DOC{ref:'Model'} may be used in place of instances of the $$DOC{ref:'Model'} you extend.</p> */} }, { name: 'traits', type: 'Array[String]', view: 'foam.ui.StringArrayView', defaultValueFn: function() { return []; }, help: 'Traits to mix-into this Model.', documentation: function() { /* Traits allow you to mix extra features into your $$DOC{ref:'Model'} through composition, avoiding inheritance where unecesssary. */} }, { name: 'plural', type: 'String', displayWidth: 70, displayHeight: 1, defaultValueFn: function() { return this.name + 's'; }, help: 'The plural form of this model\'s name.', documentation: function() { /* The plural form of $$DOC{ref:'Model.name'}, for use in database table naming, labels and documentation. The format generally follows the same contsraints as $$DOC{ref:'.name'}. */} }, { name: 'version', type: 'int', defaultValue: 1, help: 'Version number of model.', documentation: function() { /* For backwards compatibility, major changes should be marked by incrementing the version number. */} }, { name: 'ids', label: 'Key Properties', type: 'Array[String]', view: 'foam.ui.StringArrayView', defaultValueFn: function() { var id = this.getProperty('id'); if ( id ) return ['id']; return [this.getRuntimeProperties()[0].name]; }, help: 'Properties which make up unique id.', documentation: function() { /* An optional list of names of $$DOC{ref:'Property',usePlural:true} from this $$DOC{ref:'Model'}, which can be used together as a primary key. The $$DOC{ref:'Property',usePlural:true}, when combined, should uniquely identify an instance of your $$DOC{ref:'Model'}. $$DOC{ref:'DAO',usePlural:true} that support indexing can use this as a suggestion on how to index instances of your $$DOC{ref:'Model'}. */} }, { name: 'requires', type: 'Array[String]', view: 'foam.ui.StringArrayView', defaultValueFn: function() { return []; }, help: 'Model imports.', documentation: function() { /* <p>List of model imports, as strings of the form: <code>'Model-Path [as Alias]'</code>.</p> <p>Aliases are created on your instances that reference the full path of the model, taking it from your this.X $$DOC{ref:'developerDocs.Context', text:'context'}.</p> <p>For example:</p> <p><code>requires: [ 'mypackage.DataLayer.BigDAO', 'mypackage.UI.SmallTextView as TextView' ]<br/> ...<br/> // in your Model's methods: <br/> this.BigDAO.create(); // equivalent to this.X.mypackage.DataLayer.BigDAO.create()<br/> this.TextView.create(); // equivalent to this.X.mypackage.UI.SmallTextView.create()<br/> </code></p> */} }, { name: 'imports', type: 'Array[String]', view: 'foam.ui.StringArrayView', defaultValueFn: function() { return []; }, help: 'Context imports.', documentation: function() { /* <p>List of context items to import, as strings of the form: <code>Key [as Alias]</code>.</p> <p>Imported items are installed into your $$DOC{ref:'Model'} as pseudo-properties, using their $$DOC{ref:'Model.name', text:'name'} or the alias specified here.</p> <p><code>imports: [ 'selectedItem', 'selectionDAO as dao' ]<br/> ...<br/> // in your Model's methods: <br/> this.selectedItem.get(); // equivalent to this.X.selectedItem.get()<br/> this.dao.select(); // equivalent to this.X.selectionDAO.select()<br/> </code></p> <p>If you have $$DOC{ref:'.exports',text:'exported'} properties from a $$DOC{ref:'Model'} in a parent context, you can import those items and give them aliases for convenient access without the <code>this.X</code>.</p> <p>You can also re-export items you have imported, either with a different name or to replace the item you imported with a different property. While everyone can see changes to the value inside the imported property, only children (instances you create in your $$DOC{ref:'Model'}) will see $$DOC{ref:'Model.exports'} replacing the property itself. */} }, { name: 'exports', type: 'Array[String]', view: 'foam.ui.StringArrayView', defaultValueFn: function() { return []; }, help: 'Context exports.', documentation: function() { /* <p>A list of $$DOC{ref:'Property',usePlural:true} to export to your sub-context, as strings of the form: <code>PropertyName [as Alias]</code>.</p> <p>Properties you wish to share with other instances you create (like sub-$$DOC{ref:'foam.ui.View',usePlural:true}) can be exported automatically by listing them here. You are automatically sub-contexted, so your parent context does not see exported properties. In other words, exports are seen by children, not by parents.</p> <p>Instances you create can declare $$DOC{ref:'Model.imports'} to conveniently grab your exported items from the context.<p> <p><code>MODEL({ name: firstModel<br/> &nbsp;&nbsp; exports: [ 'myProperty', 'name as parentName' ],<br/> &nbsp;&nbsp; properties: [<br/> &nbsp;&nbsp; {<br/> &nbsp;&nbsp;&nbsp;&nbsp; name: 'proper',<br/> <br/> &nbsp;&nbsp;&nbsp;&nbsp; // This property will create a DetailView for us<br/> &nbsp;&nbsp;&nbsp;&nbsp; view: { factory_: 'foam.ui.DetailView',<br/> <br/> v &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // we can import the properties our creator exported.<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; imports: [ 'myProperty', 'parentName' ],<br/> <br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; methods: { toHTML: function() {<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // our context is provided by firstModel, so:<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.myProperty = 4; // we can see exported myProperty<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; out.print(this.parentName); // aliased, links back to our name<br/> &nbsp;&nbsp;&nbsp;&nbsp; }}},<br/> &nbsp;&nbsp;&nbsp;&nbsp; ...<br/> &nbsp;&nbsp;&nbsp;&nbsp; { name: 'myProperty' },<br/> &nbsp;&nbsp;&nbsp;&nbsp; { name: 'name' }<br/> &nbsp;&nbsp; ]<br/> &nbsp;&nbsp; ...<br/> </code></p> */} }, { name: 'implements', type: 'Array[String]', view: 'foam.ui.StringArrayView', defaultValueFn: function() { return []; }, help: 'Interfaces implemented by this Model.', documentation: function() { /* $$DOC{ref:'Interface',usePlural:true} implemented by this $$DOC{ref:'Model'} .*/} }, { name: 'tableProperties', type: 'Array[String]', view: 'foam.ui.StringArrayView', displayWidth: 70, lazyFactory: function() { return (this.properties || this.properties_).filter(function(o) { return !o.hidden; }).map(function(o) { return o.name; }); }, help: 'Properties to be displayed in table view. Defaults to all properties.', documentation: function() { /* Indicates the $$DOC{ref:'Property',usePlural:true} to display when viewing a list of instances of this $$DOC{ref:'Model'} in a table or other $$DOC{ref:'Property'} viewer. */} }, { name: 'searchProperties', type: 'Array[String]', view: 'foam.ui.StringArrayView', displayWidth: 70, defaultValueFn: function() { return this.tableProperties; }, help: 'Properties display in a search view. Defaults to table properties.', documentation: function() { /* Indicates the $$DOC{ref:'Property',usePlural:true} to display when viewing of this $$DOC{ref:'Model'} in a search view. */} }, { // model_: 'ArrayProperty', name: 'properties', subType: 'Property', view: 'foam.ui.ArrayView', factory: function() { return []; }, defaultValue: [], help: 'Properties associated with the entity.', preSet: function(oldValue, newValue) { // Convert Maps to Properties if required for ( var i = 0 ; i < newValue.length ; i++ ) { var p = newValue[i]; if ( typeof p === 'string' ) newValue[i] = p = { name: p }; if ( ( ( ! DEBUG ) && p.debug ) && ( ! p.model_ || typeof p.model_ === 'string' ) ) { newValue.splice(i,1); i--; continue; } if ( ! p.model_ ) { p = newValue[i] = Property.create(p); } else if ( typeof p.model_ === 'string' ) { p = newValue[i] = JSONUtil.mapToObj(this.X, p); } // create property constant this[constantize(p.name)] = newValue[i]; } this.propertyMap_ = null; return newValue; }, documentation: function() { /* <p>The $$DOC{ref:'Property',usePlural:true} of a $$DOC{ref:'Model'} act as data members and connection points. A $$DOC{ref:'Property'} can store a modelled value, and bind to other $$DOC{ref:'Property',usePlural:true} for easy reactive programming.</p> <p>Note that, like $$DOC{ref:'Model'} being a $$DOC{ref:'Model'} itself, the $$DOC{ref:'Model.properties'} feature of all models is itself a $$DOC{ref:'Property'}. */} }, { name: 'actions', type: 'Array[Action]', subType: 'Action', view: 'foam.ui.ArrayView', factory: function() { return []; }, propertyToJSON: function(visitor, output, o) { if ( o[this.name].length ) output[this.name] = o[this.name]; }, defaultValue: [], help: 'Actions associated with the entity.', preSet: function(_, newValue) { if ( ! Action ) return newValue; // Convert Maps to Properties if required for ( var i = 0 ; i < newValue.length ; i++ ) { var p = newValue[i]; if ( ! p.model_ ) { newValue[i] = Action.create(p); } else if ( typeof p.model_ === 'string' ) { newValue[i] = FOAM(p); } // create property constant if ( p.name ) this[constantize(p.name)] = newValue[i]; } return newValue; }, documentation: function() { /* <p>$$DOC{ref:'Action',usePlural:true} implement a behavior and attach a label, icon, and typically a button-like $$DOC{ref:'foam.ui.View'} or menu item to activate the behavior.</p> */} }, { name: 'constants', type: 'Array[Constant]', subType: 'Constant', view: 'foam.ui.ArrayView', factory: function() { return []; }, propertyToJSON: function(visitor, output, o) { if ( o[this.name].length ) output[this.name] = o[this.name]; }, defaultValue: [], help: 'Constants associated with the entity.', preSet: function(_, newValue) { if ( ! Constant ) return newValue; if ( Array.isArray(newValue) ) return JSONUtil.arrayToObjArray(this.X, newValue, Constant); // convert a map of values to an array of Constant objects var constants = []; for ( var key in newValue ) { var oldValue = newValue[key]; var constant = Constant.create({ name: key, value: oldValue }); constants.push(constant); } return constants; } }, { name: 'messages', type: 'Array[Message]', subType: 'Constant', view: 'foam.ui.ArrayView', factory: function() { return []; }, propertyToJSON: function(visitor, output, o) { if ( o[this.name].length ) output[this.name] = o[this.name]; }, defaultValue: [], help: 'Messages associated with the entity.', preSet: function(_, newValue) { if ( ! GLOBAL.Message ) return newValue; if ( Array.isArray(newValue) ) return JSONUtil.arrayToObjArray(this.X, newValue, Message); // convert a map of values to an array of Message objects var messages = []; for ( var key in newValue ) { var oldValue = newValue[key]; var message = Message.create({ name: key, value: oldValue }); messages.push(message); } return messages; } }, { model_: 'ArrayProperty', name: 'methods', subType: 'Method', help: 'Methods associated with the entity.', adapt: function(_, a) { if ( ! Method ) return a; function createMethod(X, name, fn) { var method = Method.create({ name: name, code: fn }); if ( DEBUG && Arg ) { var str = fn.toString(); method.args = str. match(/^function[ _$\w]*\(([ ,\w]*)/)[1]. split(','). filter(function(name) { return name; }). map(function(name) { return Arg.create({name: name.trim()}); }); } return method; } if ( Array.isArray(a) ) { for ( var i = 0 ; i < a.length ; i++ ) { a[i] = ( typeof a[i] === 'function' ) ? createMethod(this.X, a[i].name, a[i]) : JSONUtil.mapToObj(this.X, a[i], Method, seq) ; } return a; } // convert a map of functions to an array of Method instances, DEPRECATED var methods = []; for ( var key in a ) methods.push(createMethod(this.X, key, a[key])); return methods; }, documentation: function() { /* <p>$$DOC{ref:'Method',usePlural:true} contain code that runs in the instance's scope, so code in your $$DOC{ref:'Method'} has access to the other $$DOC{ref:'Property',usePlural:true} and features of your $$DOC{ref:'Model'}.</p> <ul> <li><code>this.propertyName</code> gives the value of a $$DOC{ref:'Property'}</li> <li><code>this.propertyName$</code> is the binding point for the $$DOC{ref:'Property'}. Assignment will bind bi-directionally, or <code>Events.follow(src, dst)</code> will bind from src to dst.</li> <li><code>this.methodName</code> calls another $$DOC{ref:'Method'} of this $$DOC{ref:'Model'}</li> <li><code>this.SUPER()</code> calls the $$DOC{ref:'Method'} implementation from the base $$DOC{ref:'Model'} (specified in $$DOC{ref:'Model.extendsModel'}). Calling <code>this.SUPER()</code> is extremely important in your <code>init()</code> $$DOC{ref:'Method'}, if you provide one.</li> </ul> <p>In JSON, $$DOC{ref:'Model.methods'} may be specified as a dictionary:</p> <p><code>methods: { methodName: function(arg1) { ...your code here... }, anotherMethod: ... }</code></p> */} }, { name: 'listeners', type: 'Array[Method]', subType: 'Method', view: 'foam.ui.ArrayView', factory: function() { return []; }, propertyToJSON: function(visitor, output, o) { if ( o[this.name].length ) output[this.name] = o[this.name]; }, preSet: function(_, newValue) { if ( Array.isArray(newValue) ) return JSONUtil.arrayToObjArray(this.X, newValue, Method); return newValue; }, defaultValue: [], help: 'Event listeners associated with the entity.', documentation: function() { /* <p>The $$DOC{ref:'Model.listeners'} $$DOC{ref:'Property'} contains a list of $$DOC{ref:'Method',usePlural:true}, but is separate and differs from the $$DOC{ref:'Model.methods'} $$DOC{ref:'Property'} in how the scope is handled. For a listener, <code>this</code> is bound to your instance, so when the listener is invoked by an event from elsewhere in the system it can still access the features of its $$DOC{ref:'Model'} instance.</p> <p>In javascript, listeners are connected using <code>OtherProperty.addListener(myModelInstance.myListener);</code></p> */} }, /* { name: 'topics', type: 'Array[topic]', subType: 'Topic', view: 'foam.ui.ArrayView', factory: function() { return []; }, defaultValue: [], help: 'Event topics associated with the entity.' }, */ { name: 'templates', type: 'Array[Template]', subType: 'Template', view: 'foam.ui.ArrayView', factory: function() { return []; }, propertyToJSON: function(visitor, output, o) { if ( o[this.name].length ) output[this.name] = o[this.name]; }, defaultValue: [], postSet: function(_, templates) { TemplateUtil.expandModelTemplates(this); }, // defaultValueFn: function() { return []; }, help: 'Templates associated with this entity.', documentation: function() { /* The $$DOC{ref:'Template',usePlural:true} to process and install into instances of this $$DOC{ref:'Model'}. $$DOC{ref:'foam.ui.View',usePlural:true} created inside each $$DOC{ref:'Template'} using the $$DOC{ref:'.templates',text:'$$propertyName{args}'} view creation tag become available as <code>myInstance.propertyNameView</code>. */} }, { name: 'models', type: 'Array[Model]', subType: 'Model', view: 'foam.ui.ArrayView', factory: function() { return []; }, propertyToJSON: function(visitor, output, o) { if ( o[this.name].length ) output[this.name] = o[this.name]; }, adapt: function(_, newValue) { if ( ! Model ) return newValue; return Array.isArray(newValue) ? JSONUtil.arrayToObjArray(this.X, newValue, Model) : newValue; }, postSet: function(_, models) { for ( var i = 0 ; i < models.length ; i++ ) this[models[i].name] = models[i]; }, defaultValue: [], help: 'Sub-models embedded within this model.', documentation: function() { /* $$DOC{ref:'Model',usePlural:true} may be nested inside one another to better organize them. $$DOC{ref:'Model',usePlural:true} declared this way do not gain special access to their containing $$DOC{ref:'Model'}, but are only accessible through their container. */} }, { name: 'tests', label: 'Unit Tests', type: 'Array[Unit Test]', subType: 'UnitTest', view: 'foam.ui.ArrayView', factory: function() { return []; }, propertyToJSON: function(visitor, output, o) { if ( o[this.name].length ) output[this.name] = o[this.name]; }, adapt: function(_, a) { if ( ! a ) return a; for ( var i = 0 ; i < a.length ; i++ ) { if ( typeof a[i] === "function" ) { a[i] = UnitTest.create({ name: a[i].name, code: a[i] }); } } return a; }, defaultValue: [], help: 'Unit tests associated with this model.', documentation: function() { /* Create $$DOC{ref:'UnitTest',usePlural:true} that should run to test the functionality of this $$DOC{ref:'Model'} here. */} }, { name: 'relationships', subType: 'Relationship', view: 'foam.ui.ArrayView', factory: function() { return []; }, propertyToJSON: function(visitor, output, o) { if ( o[this.name].length ) output[this.name] = o[this.name]; }, defaultValue: [], help: 'Relationships of this model to other models.', preSet: function(_, newValue) { if ( ! Relationship ) return newValue; // Convert Maps to Relationships if required for ( var i = 0 ; i < newValue.length ; i++ ) { var p = newValue[i]; if ( ! p.model_ ) { p = newValue[i] = Relationship.create(p); } else if ( typeof p.model_ === 'string' ) { p = newValue[i] = FOAM(p); } // create property constant this[constantize(p.name)] = newValue[i]; } return newValue; }, documentation: function() { /* <p>$$DOC{ref:'Relationship',usePlural:true} indicate a parent-child relation between instances of this $$DOC{ref:'Model'} and the indicated $$DOC{ref:'Model',usePlural:true}, through the indicated $$DOC{ref:'Property',usePlural:true}. If your $$DOC{ref:'Model',usePlural:true} build a tree structure of instances, they could likely benefit from a declared $$DOC{ref:'Relationship'}. </p> */} }, { name: 'issues', type: 'Array[Issue]', subType: 'Issue', debug: true, view: 'foam.ui.ArrayView', factory: function() { return []; }, propertyToJSON: function(visitor, output, o) { if ( o[this.name].length ) output[this.name] = o[this.name]; }, defaultValue: [], help: 'Issues associated with this model.', documentation: function() { /* Bug tracking inside the FOAM system can attach $$DOC{ref:'Issue',usePlural:true} directly to the affected $$DOC{ref:'Model',usePlural:true}. */} }, { name: 'help', label: 'Help Text', type: 'String', displayWidth: 70, displayHeight: 6, view: 'foam.ui.TextAreaView', defaultValue: '', help: 'Help text associated with the entity.', documentation: function() { /* This $$DOC{ref:'.help'} text informs end users how to use the $$DOC{ref:'Model'} or $$DOC{ref:'Property'}, through field labels or tooltips. */} }, { name: 'i18nComplete_', defaultValue: false, hidden: true, transient: true }, { name: 'translationHint', label: 'Description for Translation', type: 'String', defaultValueFn: function() { return this.name; } }, DocumentationBootstrap, { name: 'notes', type: 'String', displayWidth: 70, displayHeight: 6, view: 'foam.ui.TextAreaView', defaultValue: '', help: 'Internal documentation associated with this entity.', documentation: function() { /* Internal documentation or implementation-specific 'todo' notes. */} }, { name: 'createActionFactory', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, rows:3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'Factory to create the action object for creating this object', documentation: function() { /* Factory to create the action object for creating this object */} }, { name: 'deleteActionFactory', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, rows:3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'Factory to create the action object for deleting this object', documentation: function() { /* Factory to create the action object for deleting this object */} } ], //templates:[ // { // model_: 'Template', // name: 'javaSource', // description: 'Java Source', // "template": "// Generated by FOAM, do not modify.\u000a// Version <%= this.version %>\u000a<%\u000a var className = this.javaClassName;\u000a var parentClassName = this.extendsModel ? this.extendsModel : 'FObject';\u000a\u000a if ( GLOBAL[parentClassName] && GLOBAL[parentClassName].abstract ) parentClassName = 'Abstract' + parentClassName;\u000a\u000a%>\u000a<% if ( this.package ) { %>\\\u000apackage <%= this.package %>;\u000a\u000a<% } %>\\\u000aimport foam.core.*;\u000a\u000apublic<%= this.abstract ? ' abstract' : '' %> class <%= className %>\u000a extends <%= parentClassName %>\u000a{\u000a <% for ( var key in this.properties ) { var prop = this.properties[key]; %>\u000a public final static Property <%= constantize(prop.name) %> = new Abstract<%= prop.javaType.capitalize() %>Property() {\u000a public String getName() { return \"<%= prop.name %>_\"; }\u000a public String getLabel() { return \"<%= prop.label %>\"; }\u000a public Object get(Object o) { return ((<%= this.name %>) o).get<%= prop.name.capitalize() %>(); }\u000a public void set(Object o, Object v) { ((<%= this.name %>) o).set<%= prop.name.capitalize() %>(toNative(v)); }\u000a public int compare(Object o1, Object o2) { return compareValues(((<%= this.name%>)o1).<%= prop.name %>_, ((<%= this.name%>)o2).<%= prop.name %>_); }\u000a };\u000a <% } %>\u000a\u000a final static Model model__ = new AbstractModel(new Property[] {<% for ( var key in this.properties ) { var prop = this.properties[key]; %> <%= constantize(prop.name) %>,<% } %> }) {\u000a public String getName() { return \"<%= this.name %>\"; }\u000a public String getLabel() { return \"<%= this.label %>\"; }\u000a public Property id() { return <%= this.ids.length ? constantize(this.ids[0]) : 'null' %>; }\u000a };\u000a\u000a public Model model() {\u000a return model__;\u000a }\u000a public static Model MODEL() {\u000a return model__;\u000a }\u000a\u000a <% for ( var key in this.properties ) { var prop = this.properties[key]; %>\u000a private <%= prop.javaType %> <%= prop.name %>_; <% } %>\u000a\u000a public <%= className %>()\u000a {\u000a }\u000a<% if ( this.properties.length ) { %> \u000a public <%= className %>(<% for ( var key in this.properties ) { var prop = this.properties[key]; %><%= prop.javaType, ' ', prop.name, key < this.properties.length-1 ? ', ': '' %><% } %>)\u000a { <% for ( var key in this.properties ) { var prop = this.properties[key]; %>\u000a <%= prop.name %>_ = <%= prop.name %>; <% } %>\u000a }\u000a<% } %>\u000a\u000a <% for ( var key in this.properties ) { var prop = this.properties[key]; %>\u000a public <%= prop.javaType %> get<%= prop.name.capitalize() %>() {\u000a return <%= prop.name %>_;\u000a };\u000a public void set<%= prop.name.capitalize() %>(<%= prop.javaType, ' ', prop.name %>) {\u000a <%= prop.name %>_ = <%= prop.name %>;\u000a };\u000a <% } %>\u000a\u000a public int hashCode() { \u000a int hash = 1;\u000a <% for ( var key in this.properties ) { var prop = this.properties[key]; %>\u000a hash = hash * 31 + hash(<%= prop.name %>_); <% } %>\u000a\u000a return hash;\u000a }\u000a\u000a public int compareTo(Object obj) {\u000a if ( obj == this ) return 0;\u000a if ( obj == null ) return 1;\u000a\u000a <%= this.name %> other = (<%= this.name %>) obj;\u000a \u000a int cmp;\u000a <% for ( var key in this.properties ) { var prop = this.properties[key]; %>\u000a if ( ( cmp = compare(get<%= prop.name.capitalize() %>(), other.get<%= prop.name.capitalize() %>()) ) != 0 ) return cmp; <% } %>\u000a\u000a return 0;\u000a }\u000a\u000a public StringBuilder append(StringBuilder b) {\u000a return b\u000a <% for ( var key in this.properties ) { var prop = this.properties[key]; %>\\\u000a .append(\"<%= prop.name %>=\").append(get<%= prop.name.capitalize() %>())<%= key < this.properties.length-1 ? '.append(\", \")' : '' %> \u000a <% } %> ;\u000a }\u000a\u000a public Object fclone() {\u000a <%= this.name %> c = new <%= this.name %>();\u000a <% for ( var key in this.properties ) { var prop = this.properties[key]; %>\\\u000ac.set<%= prop.name.capitalize() %>(get<%= prop.name.capitalize() %>());\u000a <% } %>\\\u000areturn c;\u000a }\u000a\u000a}" // }, // { // model_: 'Template', // name: 'closureExterns', // description: 'Closure Externs JavaScript Source', // template: '/**\n' + // ' * @constructor\n' + // ' */\n' + // '<%= this.name %> = function() {};\n' + // '<% for ( var i = 0 ; i < this.properties.length ; i++ ) { var prop = this.properties[i]; %>' + // '\n<%= prop.closureSource(undefined, this.name) %>\n' + // '<% } %>' + // '<% for ( var i = 0 ; i < this.methods.length ; i++ ) { var meth = this.methods[i]; %>' + // '\n<%= meth.closureSource(undefined, this.name) %>\n' + // '<% } %>' // }, // { // model_: 'Template', // name: 'dartSource', // description: 'Dart Class Source', // template: '<% out(this.name); %>\n{\n<% for ( var key in this.properties ) { var prop = this.properties[key]; %> var <%= prop.name %>;\n<% } %>\n\n <%= this.name %>()\n {\n\n }\n\n <%= this.name %>(<% for ( var key in this.properties ) { var prop = this.properties[key]; %>this.<%= prop.name, key < this.properties.length-1 ? ", ": "" %><% } %>)\n}' // }, // { // model_: 'Template', // name: 'protobufSource', // description: 'Protobuf source', // template: 'message <%= this.name %> {\n<% for (var i = 0, prop; prop = this.properties[i]; i++ ) { if ( prop.prototag == null ) continue; if ( prop.help ) { %>//<%= prop.help %>\n<% } %> <% if ( prop.type.startsWith("Array") ) { %>repeated<% } else if ( false ) { %>required<% } else { %>optional<% } %> <%= prop.protobufType %> <%= prop.name %> = <%= prop.prototag %>;\n\n<% } %>}\n' // } //], toString: function() { return "Model"; } }; /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ var Property = { __proto__: BootstrapModel, instance_: {}, name: 'Property', plural:'Properties', help: 'Describes a properties of a modelled entity.', ids: [ 'name' ], tableProperties: [ 'name', 'label', 'type', 'required', 'defaultValue' ], documentation: function() { /* <p>The $$DOC{ref:'Property',usePlural:true} of a $$DOC{ref:'Model'} act as data members and connection points. A $$DOC{ref:'Property'} can store a modelled value, and bind to other $$DOC{ref:'Property',usePlural:true} for easy reactive programming.</p> <p>Note that, like $$DOC{ref:'Model'} being a $$DOC{ref:'Model'} itself, the $$DOC{ref:'Model.properties'} feature of all models is itself a $$DOC{ref:'Property'}. <p> */}, properties: [ { name: 'name', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', help: 'The coding identifier for the property.', documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}. $$DOC{ref:'.name'} should generally only contain identifier-safe characters. $$DOC{ref:'.'} names should use camelCase staring with a lower case letter. */} }, { name: 'label', type: 'String', required: false, displayWidth: 70, displayHeight: 1, defaultValueFn: function() { return labelize(this.name); }, help: 'The display label for the property.', documentation: function() { /* A human readable label for the $$DOC{ref:'.'}. May contain spaces or other odd characters. */} }, { name: 'speechLabel', type: 'String', required: false, displayWidth: 70, displayHeight: 1, defaultValueFn: function() { return this.label; }, help: 'The speech label for the property.', documentation: function() { /* A speakable label for the $$DOC{ref:'.'}. Used for accesibility. */} }, { name: 'tableLabel', type: 'String', displayWidth: 70, displayHeight: 1, defaultValueFn: function() { return this.label; }, help: 'The table display label for the entity.', documentation: function() { /* A human readable label for the $$DOC{ref:'Model'} for use in tables. May contain spaces or other odd characters. */} }, { name: 'type', type: 'String', required: true, // todo: curry arguments view: { factory_: 'foam.ui.ChoiceView', choices: [ 'Array', 'Boolean', 'Color', 'Date', 'DateTime', 'Email', 'Enum', 'Float', 'Function', 'Image', 'Int', 'Object', 'Password', 'String', 'String[]', 'URL' ] }, defaultValue: 'String', help: 'The type of the property.', documentation: function() { /* <p>The type of the $$DOC{ref:'.'}, either a primitive type or a $$DOC{ref:'Model'}.</p> <p>Primitives include:</p> <ul> <li>Array</li> <li>Boolean</li> <li>Color</li> <li>Date</li> <li>DateTime</li> <li>Email</li> <li>Enum</li> <li>Float</li> <li>Function</li> <li>Image</li> <li>Int</li> <li>Object</li> <li>Password</li> <li>String</li> <li>String[]</li> <li>URL</li> </ul> */} }, { name: 'protobufType', type: 'String', required: false, help: 'The protobuf type that represents the type of this property.', defaultValueFn: function() { return this.type.toLowerCase(); }, documentation: function() {/* When generating protobuf definitions, specifies the type to use for the field this represents. */} }, { name: 'javaType', type: 'String', required: false, defaultValueFn: function() { return this.type; }, help: 'The java type that represents the type of this property.', documentation: function() { /* When running FOAM in a Java environment, specifies the Java type or class to use. */} }, { name: 'javascriptType', type: 'String', required: false, defaultValueFn: function() { return this.type; }, help: 'The javascript type that represents the type of this property.', documentation: function() { /* When running FOAM in a javascript environment, specifies the javascript type to use. */} }, { name: 'shortName', type: 'String', required: true, displayWidth: 10, displayHeight: 1, defaultValue: '', help: 'A short alternate name to be used for compact encoding.', documentation: "A short alternate $$DOC{ref:'.name'} to be used for compact encoding." }, { name: 'singular', type: 'String', required: false, displayWidth: 70 }, { name: 'aliases', type: 'Array[String]', view: 'foam.ui.StringArrayView', defaultValue: [], help: 'Alternate names for this property.', documentation: function() { /* Aliases can be used as synonyms for this $$DOC{ref:'Property'} in code or to look it up by name. */} }, { name: 'mode', type: 'String', defaultValue: 'read-write', view: { factory_: 'foam.ui.ChoiceView', choices: ['read-only', 'read-write', 'final'] }, documentation: function() { /* To restrict modification to a $$DOC{ref:'Property'}, the $$DOC{ref:'.mode'} can be set to read-only to block changes, or to final to block overriding this $$DOC{ref:'Property'} in descendents of the $$DOC{ref:'Model'} that owns this $$DOC{ref:'Property'}. */} }, { name: 'subType', label: 'Sub-Type', type: 'String', displayWidth: 30, // todo: keyView of Models help: 'The type of the property.', documentation: function() { /* In array types, the $$DOC{ref:'.subType'} indicates the type that the array contains. */} }, { name: 'units', type: 'String', required: true, displayWidth: 70, displayHeight: 1, defaultValue: '', help: 'The units of the property.', documentation: function() { /* The units of the $$DOC{ref:'Property'}. */} }, { name: 'required', type: 'Boolean', view: 'foam.ui.BooleanView', defaultValue: true, help: 'Indicates if the property is a required field.', documentation: function() { /* Indicates whether the $$DOC{ref:'Property'} is required for its owner $$DOC{ref:'Model'} to function properly. */} }, { name: 'hidden', type: 'Boolean', view: 'foam.ui.BooleanView', defaultValue: false, help: 'Indicates if the property is hidden.', documentation: function() { /* Indicates whether the $$DOC{ref:'Property'} is for internal use and should be hidden from the user when viewing tables or other views of $$DOC{ref:'Model'} $$DOC{ref:'Property',usePlural:true}. */} }, { name: 'transient', type: 'Boolean', view: 'foam.ui.BooleanView', defaultValue: false, help: 'Indicates if the property is transient.', documentation: function() { /* Indicates whether the $$DOC{ref:'Property'} is transient, and should not be saved permanently or serialized. */} }, { name: 'displayWidth', type: 'int', displayWidth: 8, displayHeight: 1, defaultValue: '30', help: 'The display width of the property.', documentation: function() { /* A width suggestion for views that automatically render the $$DOC{ref:'Property'}. */} }, { name: 'displayHeight', type: 'int', displayWidth: 8, displayHeight: 1, defaultValue: 1, help: 'The display height of the property.', documentation: function() { /* A height suggestion for views that automatically render the $$DOC{ref:'Property'}. */} }, { model_: 'ViewFactoryProperty', name: 'view', type: 'view', defaultValue: 'foam.ui.TextFieldView', help: 'View component for the property.', documentation: function() { /* The default $$DOC{ref:'foam.ui.View'} to use when rendering the $$DOC{ref:'Property'}. Specify a string or an object with factory_ and other properties specified. */} }, { model_: 'ViewFactoryProperty', name: 'detailView', type: 'view', defaultValueFn: function() { return this.view; }, help: 'View component for the property when rendering within a DetailView.', documentation: function() { /* The default $$DOC{ref:'foam.ui.View'} to use when rendering the $$DOC{ref:'Property'} as a part of a $$DOC{ref:'foam.ui.DetailView'}. Specify a string or an object with factory_ and other properties specified. */} }, { model_: 'ViewFactoryProperty', name: 'citationView', type: 'view', defaultValueFn: function() { return this.view; }, help: 'View component for the property when rendering within a CitationView.', documentation: function() { /* The default $$DOC{ref:'foam.ui.View'} to use when rendering the $$DOC{ref:'Property'} as a part of a $$DOC{ref:'CitationView'}. Specify a string or an object with factory_ and other properties specified. */} }, { // model_: 'FunctionProperty', name: 'detailViewPreRow', defaultValue: function() { return ""; }, help: 'Inject HTML before row in DetailView.', documentation: function() { /* An optional function to inject HTML before the row in $$DOC{ref:'foam.ui.DetailView'}. */} }, { // model_: 'FunctionProperty', name: 'detailViewPostRow', defaultValue: function() { return ""; }, help: 'Inject HTML before row in DetailView.', documentation: function() { /* An optional function to inject HTML after the row in $$DOC{ref:'foam.ui.DetailView'}. */} }, { name: 'defaultValue', type: 'String', required: false, displayWidth: 70, displayHeight: 1, defaultValue: '', postSet: function(old, nu) { if ( nu && this.defaultValueFn ) this.defaultValueFn = undefined; }, help: 'The property\'s default value.', documentation: function() { /* An optional function to inject HTML before the row in $$DOC{ref:'foam.ui.DetailView'}. */} }, { name: 'defaultValueFn', label: 'Default Value Function', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, rows:3, view: 'foam.ui.FunctionView', defaultValue: '', postSet: function(old, nu) { if ( nu && this.defaultValue ) this.defaultValue = undefined; }, help: 'The property\'s default value function.', documentation: function() { /* Optional function that is evaluated when a default value is required. Will unset any $$DOC{ref:'.defaultValue'} that has been set. */} }, { name: 'dynamicValue', label: "Value's Dynamic Function", type: 'Function', required: false, displayWidth: 70, displayHeight: 3, rows:3, view: 'foam.ui.FunctionView', defaultValue: '', help: "A dynamic function which computes the property's value.", documentation: function() { /* Allows the value of this $$DOC{ref:'Property'} to be calculated dynamically. Other $$DOC{ref:'Property',usePlural:true} and bindable objects used inside the function will be automatically bound and the function re-evaluated when a dependency changes. */} }, { name: 'factory', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, rows:3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'Factory for creating initial value when new object instantiated.', documentation: function() { /* An optional function that creates the instance used to store the $$DOC{ref:'Property'} value. This is useful when the $$DOC{ref:'Property'} type is a complex $$DOC{ref:'Model'} that requires construction parameters. */} }, { name: 'lazyFactory', type: 'Function', required: false, view: 'foam.ui.FunctionView', help: 'Factory for creating the initial value. Only called when the property is accessed for the first time.', documentation: function() { /* Like the $$DOC{ref:'.factory'} function, but only evaulated when this $$DOC{ref:'Property'} is accessed for the first time. */} }, { name: 'getter', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'The property\'s default value function.', documentation: function() { /* For advanced use. Supplying a $$DOC{ref:'.getter'} allows you to completely re-implement the $$DOC{ref:'Property'} storage mechanism, to calculcate the value, or cache, or pre-process the value as it is requested. In most cases you can just supply a $$DOC{ref:'.preSet'} or $$DOC{ref:'.postSet'} instead. */} }, { name: 'adapt', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'An adapter function called before preSet.', documentation: function() { /* Allows you to modify the incoming value before it is set. Parameters <code>(old, nu)</code> are supplied with the old and new value. Return the value you want to be set. */} }, { name: 'preSet', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'An adapter function called before normal setter logic.', documentation: function() { /* Allows you to modify the incoming value before it is set. Parameters <code>(old, nu)</code> are supplied with the old and new value. Return the value you want to be set. */} }, { name: 'postSet', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'A function called after normal setter logic, but before property change event fired.', documentation: function() { /* Allows you to react after the value of the $$DOC{ref:'Property'} has been set, but before property change event is fired. Parameters <code>(old, nu)</code> are supplied with the old and new value. */} }, { name: 'setter', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'The property\'s default value function.', documentation: function() { /* For advanced use. Supplying a $$DOC{ref:'.setter'} allows you to completely re-implement the $$DOC{ref:'Property'} storage mechanism, to calculcate the value, or cache, or pre-process the value as it is set. In most cases you can just supply a $$DOC{ref:'.preSet'} or $$DOC{ref:'.postSet'} instead. */} }, { name: 'tableFormatter', label: 'Table Cell Formatter', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, rows:3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'Function to format value for display in TableView.', documentation: "A function to format the value for display in a $$DOC{ref:'foam.ui.TableView'}." }, { name: 'summaryFormatter', label: 'Summary Formatter', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, rows:3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'Function to format value for display in SummaryView.', documentation: "A function to format the value for display in a $$DOC{ref:'SummaryView'}." }, { name: 'tableWidth', type: 'String', required: false, defaultValue: '', help: 'Table View Column Width.', documentation: "A Suggestion for $$DOC{ref:'foam.ui.TableView'} column width." }, { name: 'help', label: 'Help Text', type: 'String', required: false, displayWidth: 70, displayHeight: 6, view: 'foam.ui.TextAreaView', defaultValue: '', help: 'Help text associated with the property.', documentation: function() { /* This $$DOC{ref:'.help'} text informs end users how to use the $$DOC{ref:'Property'}, through field labels or tooltips. */} }, DocumentationBootstrap, { name: 'prototag', label: 'Protobuf tag', type: 'Int', required: false, help: 'The protobuf tag number for this field.', documentation: 'The protobuf tag number for this field.' }, { name: 'actionFactory', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, rows:3, view: 'foam.ui.FunctionView', defaultValue: '', help: 'Factory to create the action objects for taking this property from value A to value B', documentation: "Factory to create the $$DOC{ref:'Action'} objects for taking this $$DOC{ref:'Property'} from value A to value B" }, { name: 'compareProperty', type: 'Function', view: 'foam.ui.FunctionView', displayWidth: 70, displayHeight: 5, defaultValue: function(o1, o2) { if ( o1 === o2 ) return 0; if ( ! o1 && ! o2 ) return 0; if ( ! o1 ) return -1; if ( ! o2 ) return 1; if ( o1.localeCompare ) return o1.localeCompare(o2); if ( o1.compareTo ) return o1.compareTo(o2); return o1.$UID.compareTo(o2.$UID); }, help: 'Comparator function.', documentation: "A comparator function two compare two instances of this $$DOC{ref:'Property'}." }, { name: 'fromString', defaultValue: function(s, p) { this[p.name] = s; }, help: 'Function to extract value from a String.' }, { name: 'fromElement', defaultValue: function propertyFromElement(e, p) { if ( ! p.type || ! this.X.lookup || p.type === 'String' ) { p.fromString.call(this, e.innerHTML, p); return; } var model = this.X.lookup(p.type); if ( ! model ) { p.fromString.call(this, e.innerHTML, p); return; } var o = model.create(); if ( ! o.fromElement ){ p.fromString.call(this, e.innerHTML, p); return; } this[p.name] = o.fromElement(e); }, help: 'Function to extract from a DOM Element.', documentation: "Function to extract a value from a DOM Element." }, { name: 'propertyToJSON', defaultValue: function(visitor, output, o) { if ( ! this.transient ) output[this.name] = visitor.visit(o[this.name]); }, help: 'Function to extract from a DOM Element.', documentation: "Function to extract a value from a DOM Element." }, { name: 'autocompleter', subType: 'Autocompleter', help: 'Name or model for the autocompleter for this property.', documentation: function() { /* Name or $$DOC{ref:'Model'} for the $$DOC{ref:'Autocompleter'} for this $$DOC{ref:'Property'}. */} }, { name: 'install', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, rows:3, view: 'foam.ui.FunctionView', defaultValue: '', help: "A function which installs additional features into the Model's prototype.", documentation: function() { /* A function which installs additional features into our $$DOC{ref:'Model'} prototype. This allows extra language dependent features or accessors to be added to instances for use in code. */} }, { name: 'exclusive', type: 'Boolean', view: 'foam.ui.BooleanView', defaultValue: true, help: 'Indicates if the property can only have a single value.', documentation: function() { /* Indicates if the $$DOC{ref:'Property'} can only have a single value. */} }, { name: 'memorable', type: 'Boolean', help: 'True if this value should be included in a memento for this object.', defaultValue: false } ], methods: { partialEval: function() { return this; }, f: function(obj) { return obj[this.name] }, compare: function(o1, o2) { return this.compareProperty(this.f(o1), this.f(o2)); }, toSQL: function() { return this.name; }, toMQL: function() { return this.name; }, toBQL: function() { return this.name; }, cloneProperty: function(/* this=prop, */ value) { return ( value && value.clone ) ? value.clone() : value; }, deepCloneProperty: function(/* this=prop, */ value) { return ( value && value.deepClone ) ? value.deepClone() : value; }, initPropertyAgents: function(proto, fastInit) { var prop = this; var name = prop.name; var name$_ = prop.name$_; if ( ! fastInit ) proto.addInitAgent( (this.postSet || this.setter) ? 9 : 0, name + ': ' + (this.postSet || this.setter ? 'copy arg (postSet)' : 'copy arg'), function(o, X, m) { if ( ! m ) return; if ( m.hasOwnProperty(name) ) o[name] = m[name]; if ( m.hasOwnProperty(name$_) ) o[name$_] = m[name$_]; } ); if ( this.dynamicValue ) { var dynamicValue = prop.dynamicValue; if ( Array.isArray(dynamicValue) ) { proto.addInitAgent(10, name + ': dynamicValue', function(o, X) { Events.dynamic( dynamicValue[0].bind(o), function() { o[name] = dynamicValue[1].call(o); }); }); } else { proto.addInitAgent(10, name + ': dynamicValue', function(o, X) { Events.dynamic( dynamicValue.bind(o), function(value) { o[name] = value; }); }); } } if ( this.factory ) { proto.addInitAgent(11, name + ': factory', function(o, X) { if ( ! o.hasOwnProperty(name) ) o[name]; }); } } }, //templates: [ // { // model_: 'Template', // name: 'closureSource', // description: 'Closure Externs JavaScript Source', // template: // '/**\n' + // ' * @type {<%= this.javascriptType %>}\n' + // ' */\n' + // '<%= arguments[1] %>.prototype.<%= this.name %> = undefined;' // } //], toString: function() { return "Property"; } }; Model.methods = { getProperty: BootstrapModel.getProperty, getAction: BootstrapModel.getAction, hashCode: BootstrapModel.hashCode, buildPrototype: BootstrapModel.buildPrototype, addTraitToModel_: BootstrapModel.addTraitToModel_, buildProtoImports_: BootstrapModel.buildProtoImports_, buildProtoProperties_: BootstrapModel.buildProtoProperties_, buildProtoMethods_: BootstrapModel.buildProtoMethods_, getPrototype: BootstrapModel.getPrototype, isSubModel: BootstrapModel.isSubModel, isInstance: BootstrapModel.isInstance, getAllRequires: BootstrapModel.getAllRequires, arequire: BootstrapModel.arequire, getMyFeature: BootstrapModel.getMyFeature, getRawFeature: BootstrapModel.getRawFeature, getAllMyRawFeatures: BootstrapModel.getAllMyRawFeatures, getFeature: BootstrapModel.getFeature, getAllRawFeatures: BootstrapModel.getAllRawFeatures, atest: BootstrapModel.atest, getRuntimeProperties: BootstrapModel.getRuntimeProperties }; // This is the coolest line of code that I've ever written // or ever will write. Oct. 4, 2011 -- KGR Model = Model.create(Model); Model.model_ = Model; Model.create = BootstrapModel.create; Property = Model.create(Property); // Property properties are still Bootstrap Models, so upgrade them. var ps = Property.getRuntimeProperties(); for ( var i = 0 ; i < ps.length ; i++ ) { Property[constantize(ps[i].name)] = ps[i] = Property.create(ps[i]); } USED_MODELS.Property = true; USED_MODELS.Model = true; /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ CLASS({ name: 'StringProperty', extendsModel: 'Property', help: 'Describes a properties of type String.', properties: [ { name: 'displayHeight', type: 'int', displayWidth: 8, defaultValue: 1, help: 'The display height of the property.' }, { name: 'type', type: 'String', displayWidth: 20, defaultValue: 'String', help: 'The FOAM type of this property.' }, { name: 'adapt', defaultValue: function (_, v) { return v === undefined || v === null ? '' : typeof v === 'function' ? multiline(v) : v.toString() ; } }, { name: 'javaType', type: 'String', displayWidth: 70, defaultValue: 'String', help: 'The Java type of this property.' }, { name: 'view', defaultValue: 'foam.ui.TextFieldView' }, { name: 'pattern', help: 'Regex pattern for property.' }, { name: 'prototag', label: 'Protobuf tag', type: 'Int', required: false, help: 'The protobuf tag number for this field.' } ] }); CLASS({ name: 'BooleanProperty', extendsModel: 'Property', help: 'Describes a properties of type Boolean.', properties: [ { name: 'type', type: 'String', displayWidth: 20, defaultValue: 'Boolean', help: 'The FOAM type of this property.' }, { name: 'javaType', type: 'String', displayWidth: 70, defaultValue: 'bool', help: 'The Java type of this property.' }, { name: 'view', defaultValue: 'foam.ui.BooleanView' }, { name: 'defaultValue', defaultValue: false }, { name: 'adapt', defaultValue: function (_, v) { return !!v; } }, { name: 'prototag', label: 'Protobuf tag', type: 'Int', required: false, help: 'The protobuf tag number for this field.' }, { name: 'fromString', defaultValue: function(s, p) { var txt = s.trim(); this[p.name] = txt.equalsIC('y') || txt.equalsIC('yes') || txt.equalsIC('true') || txt.equalsIC('t'); }, help: 'Function to extract value from a String.' } ] }); CLASS({ name: 'DateProperty', extendsModel: 'Property', help: 'Describes a properties of type Date.', properties: [ { name: 'type', type: 'String', displayWidth: 20, defaultValue: 'Date', help: 'The FOAM type of this property.' }, { name: 'displayWidth', defaultValue: 50 }, { name: 'javaType', type: 'String', defaultValue: 'Date', help: 'The Java type of this property.' }, { name: 'view', // TODO: create custom DateView defaultValue: 'foam.ui.DateFieldView' }, { name: 'prototag', label: 'Protobuf tag', type: 'Int', required: false, help: 'The protobuf tag number for this field.' }, { name: 'adapt', defaultValue: function (_, d) { return typeof d === 'string' ? new Date(d) : d; } }, { name: 'tableFormatter', defaultValue: function(d) { return d ? d.toRelativeDateString() : ''; } }, { name: 'compareProperty', defaultValue: function(o1, o2) { if ( ! o1 ) return ( ! o2 ) ? 0: -1; if ( ! o2 ) return 1; return o1.compareTo(o2); } } ] }); CLASS({ name: 'DateTimeProperty', extendsModel: 'DateProperty', help: 'Describes a properties of type DateTime.', properties: [ { name: 'type', type: 'String', displayWidth: 25, defaultValue: 'datetime', help: 'The FOAM type of this property.' }, { name: 'adapt', defaultValue: function(_, d) { if ( typeof d === 'number' ) return new Date(d); if ( typeof d === 'string' ) return new Date(d); return d; } }, { name: 'view', defaultValue: 'foam.ui.DateTimeFieldView' } ] }); CLASS({ name: 'IntProperty', extendsModel: 'Property', help: 'Describes a properties of type Int.', properties: [ { name: 'type', type: 'String', displayWidth: 20, defaultValue: 'Int', help: 'The FOAM type of this property.' }, { name: 'displayWidth', defaultValue: 10 }, { name: 'javaType', type: 'String', displayWidth: 10, defaultValue: 'int', help: 'The Java type of this property.' }, { name: 'view', defaultValue: 'foam.ui.IntFieldView' }, { name: 'adapt', defaultValue: function (_, v) { return typeof v === 'number' ? Math.round(v) : v ? parseInt(v) : 0 ; } }, { name: 'defaultValue', defaultValue: 0 }, { name: 'prototag', label: 'Protobuf tag', type: 'Int', required: false, help: 'The protobuf tag number for this field.' }, { name: 'compareProperty', defaultValue: function(o1, o2) { return o1 === o2 ? 0 : o1 > o2 ? 1 : -1; } } ] }); CLASS({ name: 'FloatProperty', extendsModel: 'Property', help: 'Describes a properties of type Float.', properties: [ { name: 'type', type: 'String', displayWidth: 20, defaultValue: 'Float', help: 'The FOAM type of this property.' }, { name: 'defaultValue', defaultValue: 0.0 }, { name: 'javaType', type: 'String', displayWidth: 10, defaultValue: 'double', help: 'The Java type of this property.' }, { name: 'displayWidth', defaultValue: 15 }, { name: 'view', defaultValue: 'foam.ui.FloatFieldView' }, { name: 'adapt', defaultValue: function (_, v) { return typeof v === 'number' ? v : v ? parseFloat(v) : 0.0 ; } }, { name: 'prototag', label: 'Protobuf tag', type: 'Int', required: false, help: 'The protobuf tag number for this field.' } ] }); CLASS({ name: 'FunctionProperty', extendsModel: 'Property', help: 'Describes a properties of type Function.', properties: [ { name: 'type', type: 'String', displayWidth: 20, defaultValue: 'Function', help: 'The FOAM type of this property.' }, { name: 'javaType', type: 'String', displayWidth: 10, defaultValue: 'Function', help: 'The Java type of this property.' }, { name: 'displayWidth', defaultValue: 15 }, { name: 'view', defaultValue: 'foam.ui.FunctionView' }, { name: 'defaultValue', defaultValue: function() {} }, { name: 'fromElement', defaultValue: function(e, p) { var txt = e.innerHTML.trim(); this[p.name] = txt.startsWith('function') ? eval('(' + txt + ')') : new Function(txt) ; } }, { name: 'adapt', defaultValue: function(_, value) { if ( typeof value === 'string' ) { return value.startsWith('function') ? eval('(' + value + ')') : new Function(value); } return value; } } ] }); CLASS({ name: 'ArrayProperty', extendsModel: 'Property', help: 'Describes a properties of type Array.', properties: [ { name: 'type', type: 'String', displayWidth: 20, defaultValue: 'Array', help: 'The FOAM type of this property.' }, { name: 'singular', type: 'String', displayWidth: 70, defaultValueFn: function() { return this.name.replace(/s$/, ''); }, help: 'The plural form of this model\'s name.', documentation: function() { /* The singular form of $$DOC{ref:'Property.name'}.*/} }, { name: 'subType', type: 'String', displayWidth: 20, defaultValue: '', help: 'The FOAM sub-type of this property.' }, { name: 'protobufType', defaultValueFn: function() { return this.subType; } }, { name: 'adapt', defaultValue: function(_, a, prop) { var m = prop.subType_ || ( prop.subType_ = this.X.lookup(prop.subType) || GLOBAL.lookup(prop.subType) ); if ( m ) { for ( var i = 0 ; i < a.length ; i++ ) { if ( ! m.isInstance(a[i]) ) a[i] = a[i].model_ ? FOAM(a[i]) : m.create(a[i]); } } return a; } }, { name: 'postSet', defaultValue: function(oldA, a, prop) { var name = prop.nameArrayRelay_ || ( prop.nameArrayRelay_ = prop.name + 'ArrayRelay_' ); var l = this[name] || ( this[name] = function() { this.propertyChange(prop.name, null, this[prop.name]); }.bind(this) ); if ( oldA && oldA.unlisten ) oldA.unlisten(l); if ( a && a.listen ) a.listen(l); } }, { name: 'javaType', type: 'String', displayWidth: 10, defaultValueFn: function(p) { return p.subType + '[]'; }, help: 'The Java type of this property.' }, { name: 'view', defaultValue: 'foam.ui.ArrayView' }, { name: 'factory', defaultValue: function() { return []; } }, { name: 'propertyToJSON', defaultValue: function(visitor, output, o) { if ( ! this.transient && o[this.name].length ) output[this.name] = visitor.visitArray(o[this.name]); } }, { name: 'install', defaultValue: function(prop) { defineLazyProperty(this, prop.name + '$Proxy', function() { var proxy = this.X.lookup('foam.dao.ProxyDAO').create({delegate: this[prop.name].dao}); this.addPropertyListener(prop.name, function(_, _, _, a) { proxy.delegate = a.dao; }); return { get: function() { return proxy; }, configurable: true }; }); this.addMethod('get' + capitalize(prop.singular), function(id) { for ( var i = 0; i < this[prop.name].length; i++ ) { if ( this[prop.name][i].id === id ) return this[prop.name][i]; } }); } }, { name: 'fromElement', defaultValue: function(e, p) { var model = this.X.lookup(e.getAttribute('model') || p.subType); var children = e.children; var a = []; for ( var i = 0 ; i < children.length ; i++ ) { var o = model.create(null, this.Y); o.fromElement(children[i], p); a.push(o); } this[p.name] = a; } }, { name: 'prototag', label: 'Protobuf tag', type: 'Int', required: false, help: 'The protobuf tag number for this field.' } ] }); CLASS({ name: 'ReferenceProperty', extendsModel: 'Property', help: 'A foreign key reference to another Entity.', properties: [ { name: 'type', type: 'String', displayWidth: 20, defaultValue: 'Reference', help: 'The FOAM type of this property.' }, { name: 'subType', type: 'String', displayWidth: 20, defaultValue: '', help: 'The FOAM sub-type of this property.' }, { name: 'subKey', type: 'EXPR', displayWidth: 20, defaultValue: 'ID', help: 'The foreign key that this property references.' }, { name: 'javaType', type: 'String', displayWidth: 10, // TODO: should obtain primary-key type from subType defaultValueFn: function(p) { return 'Object'; }, help: 'The Java type of this property.' }, { name: 'view', defaultValue: 'foam.ui.TextFieldView' // TODO: Uncomment when all usages of ReferenceProperty/ReferenceArrayProperty fixed. // defaultValue: 'KeyView' }, { name: 'prototag', label: 'Protobuf tag', type: 'Int', required: false, help: 'The protobuf tag number for this field.' } ] }); CLASS({ name: 'StringArrayProperty', extendsModel: 'Property', help: 'An array of String values.', properties: [ { name: 'type', type: 'String', displayWidth: 20, defaultValue: 'Array[]', help: 'The FOAM type of this property.' }, { name: 'singular', type: 'String', displayWidth: 70, defaultValueFn: function() { return this.name.replace(/s$/, ''); }, help: 'The plural form of this model\'s name.', documentation: function() { /* The singular form of $$DOC{ref:'Property.name'}.*/} }, { name: 'subType', type: 'String', displayWidth: 20, defaultValue: 'String', help: 'The FOAM sub-type of this property.' }, { name: 'displayWidth', defaultValue: 50 }, { name: 'adapt', defaultValue: function(_, v) { return Array.isArray(v) ? v : [v]; } }, { name: 'factory', defaultValue: function() { return []; } }, { name: 'javaType', type: 'String', displayWidth: 10, defaultValue: 'String[]', help: 'The Java type of this property.' }, { name: 'view', defaultValue: 'foam.ui.StringArrayView' }, { name: 'prototag', label: 'Protobuf tag', type: 'Int', required: false, help: 'The protobuf tag number for this field.' }, { name: 'exclusive', defaultValue: false }, { name: 'fromString', defaultValue: function(s, p) { this[p.name] = s.split(','); } }, { name: 'fromElement', defaultValue: function(e, p) { var val = []; var name = p.singular || 'item'; for ( var i = 0 ; i < e.children.length ; i++ ) if ( e.children[i].nodeName === name ) val.push(e.children[i].innerHTML); this[p.name] = val; } } ] }); CLASS({ name: 'ModelProperty', extendsModel: 'Property', help: 'Describes a Model property.', properties: [ { name: 'type', defaultValue: 'Model' }, { name: 'getter', defaultValue: function(name) { var value = this.instance_[name]; if ( typeof value === 'undefined' ) { var prop = this.model_.getProperty(name); if ( prop && prop.defaultValueFn ) value = prop.defaultValueFn.call(this, prop); else value = prop.defaultValue; } return this.X.lookup(value); } }, { name: 'propertyToJSON', defaultValue: function(visitor, output, o) { if ( ! this.transient ) output[this.name] = o[this.name].id; } } ] }); CLASS({ name: 'ViewProperty', extendsModel: 'Property', help: 'Describes a View-Factory property.', properties: [ { name: 'adapt', doc: "Can be specified as either a function, a Model, a Model path, or a JSON object.", defaultValue: function(_, f) { if ( typeof f === 'function' ) return f; if ( typeof f === 'string' ) { return function(d, opt_X) { return (opt_X || this.X).lookup(f).create(d, opt_X || this.Y); }.bind(this); } if ( typeof f.create === 'function' ) return f.create.bind(f); if ( typeof f.model_ === 'string' ) return function(d, opt_X) { return FOAM(f, opt_X || this.Y).copyFrom(d); } console.error('******* Unknown view factory: ', f); return f; } }, { name: 'defaultValue', adapt: function(_, f) { return ViewProperty.ADAPT.defaultValue.call(this, null, f); } } ] }); CLASS({ name: 'FactoryProperty', extendsModel: 'Property', help: 'Describes a Factory property.', properties: [ { name: 'preSet', doc: "Can be specified as either a function, a Model, a Model path, or a JSON object.", defaultValue: function(_, f) { // A Factory Function if ( typeof f === 'function' ) return f; // A String Path to a Model if ( typeof f === 'string' ) return function(map, opt_X) { return (opt_X || this.X).lookup(f).create(map, opt_X || this.Y); }.bind(this); // An actual Model if ( Model.isInstance(f) ) return f.create.bind(f); // A JSON Model Factory: { factory_ : 'ModelName', arg1: value1, ... } if ( f.factory_ ) return function(map, opt_X) { var X = opt_X || this.X; var m = X.lookup(f.factory_); console.assert(m, 'Unknown Factory Model: ' + f.factory_); return m.create(f, opt_X || this.Y); }.bind(this); console.error('******* Invalid Factory: ', f); return f; } } ] }); CLASS({ name: 'ViewFactoryProperty', extendsModel: 'FactoryProperty', help: 'Describes a View Factory property.', /* Doesn't work yet! constants: { VIEW_CACHE: {} }, */ properties: [ { name: 'defaultValue', preSet: function(_, f) { return ViewFactoryProperty.ADAPT.defaultValue.call(this, null, f); } }, { name: 'defaultValueFn', preSet: function(_, f) { // return a function that will adapt the given f's return return function(prop) { // call the defaultValue function, adapt the result, return it return ViewFactoryProperty.ADAPT.defaultValue.call(this, null, f.call(this, prop)); }; } }, { name: 'fromElement', defaultValue: function(e, p) { this[p.name] = e.innerHTML_ || ( e.innerHTML_ = e.innerHTML ); } }, { name: 'adapt', doc: "Can be specified as either a function, String markup, a Model, a Model path, or a JSON object.", defaultValue: function(_, f) { // Undefined values if ( ! f ) return f; // A Factory Function if ( typeof f === 'function' ) return f; var ret; // A String Path to a Model if ( typeof f === 'string' ) { // if not a valid model path then treat as a template if ( /[^0-9a-zA-Z$_.]/.exec(f) ) { // Cache the creation of an DetailView so that we don't // keep recompiling the template var VIEW_CACHE = ViewFactoryProperty.VIEW_CACHE || ( ViewFactoryProperty.VIEW_CACHE = {} ); var viewModel = VIEW_CACHE[f]; if ( ! viewModel ) { viewModel = VIEW_CACHE[f] = Model.create({ name: 'InnerDetailView' + this.$UID, extendsModel: 'foam.ui.DetailView', templates:[{name: 'toHTML', template: f}] }); // TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO // TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO // TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO // TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO // TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO // TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO // TODO(kgr): this isn't right because compiling the View // template is async. Should create a FutureView to handle this. viewModel.arequire(); } ret = function(args, X) { return viewModel.create(args, X || this.Y); }; } else { ret = function(map, opt_X) { var model = (opt_X || this.X).lookup(f); console.assert(!!model, 'Unknown model: ' + f + ' in ' + this.name + ' property'); return model.create(map, opt_X || this.Y); }.bind(this); } ret.toString = function() { return '"' + f + '"'; }; return ret; } // An actual Model if ( Model.isInstance(f) ) return function(args, opt_X) { return f.create(args, opt_X || this.Y) }.bind(this); // A JSON Model Factory: { factory_ : 'ModelName', arg1: value1, ... } if ( f.factory_ ) { ret = function(map, opt_X) { var m = (opt_X || this.X).lookup(f.factory_); console.assert(m, 'Unknown ViewFactory Model: ' + f.factory_); return m.create(f, opt_X || this.Y).copyFrom(map); }.bind(this); ret.toString = function() { return JSON.stringify(f); }; return ret; } if ( this.X.lookup('foam.ui.BaseView').isInstance(f) ) return constantFn(f); console.error('******* Invalid Factory: ', f); return f; } } ] }); CLASS({ name: 'ReferenceArrayProperty', extendsModel: 'ReferenceProperty', properties: [ { name: 'type', defaultValue: 'Array', displayWidth: 20, help: 'The FOAM type of this property.' }, { name: 'factory', defaultValue: function() { return []; }, }, { name: 'view', defaultValue: 'foam.ui.StringArrayView', // TODO: Uncomment when all usages of ReferenceProperty/ReferenceArrayProperty fixed. // defaultValue: 'DAOKeyView' } ] }); CLASS({ name: 'EMailProperty', extendsModel: 'StringProperty' }); CLASS({ name: 'ImageProperty', extendsModel: 'StringProperty' }); CLASS({ name: 'URLProperty', extendsModel: 'StringProperty' }); CLASS({ name: 'ColorProperty', extendsModel: 'StringProperty' }); CLASS({ name: 'PasswordProperty', extendsModel: 'StringProperty' }); if ( DEBUG ) CLASS({ name: 'DocumentationProperty', extendsModel: 'Property', help: 'Describes the documentation properties found on Models, Properties, Actions, Methods, etc.', documentation: "The developer documentation for this $$DOC{ref:'.'}. Use a $$DOC{ref:'DocModelView'} to view documentation.", properties: [ { name: 'type', type: 'String', defaultvalue: 'Documentation' }, { // Note: defaultValue: for the getter function didn't work. factory: does. name: 'getter', type: 'Function', debug: true, defaultValue: function(name) { var doc = this.instance_[name] if (doc && typeof Documentation != 'undefined' && Documentation // a source has to exist (otherwise we'll return undefined below) && ( !doc.model_ // but we don't know if the user set model_ || !doc.model_.getPrototype // model_ could be a string || !Documentation.isInstance(doc) // check for correct type ) ) { // So in this case we have something in documentation, but it's not of the // "Documentation" model type, so FOAMalize it. if (doc.body) { this.instance_[name] = Documentation.create( doc ); } else { this.instance_[name] = Documentation.create({ body: doc }); } } // otherwise return the previously FOAMalized model or undefined if nothing specified. return this.instance_[name]; } }, { name: 'view', defaultValue: 'foam.ui.DetailView', debug: true }, { name: 'help', defaultValue: 'Documentation for this entity.', debug: true }, { name: 'documentation', factory: function() { return "The developer documentation for this $$DOC{ref:'.'}. Use a $$DOC{ref:'DocModelView'} to view documentation."; }, debug: true } ] }); /** * @license * Copyright 2012-2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ // Now remove BootstrapModel so nobody tries to use it // TODO: do this once no views use it directly // delete BootstrapModel; CLASS({ name: 'Action', plural: 'Actions', tableProperties: [ 'name', 'label' ], documentation: function() { /* <p>An executable behavior that can be triggered by the user. $$DOC{ref:'Action',usePlural:true} are typically represented as buttons or menu items. Activating the $$DOC{ref:'Action'} causes the $$DOC{ref:'.action'} function $$DOC{ref:'Property'} to run. The user-facing control's state is handled by $$DOC{ref:'.isEnabled'} and $$DOC{ref:'.isAvailable'}. </p> */}, properties: [ { name: 'name', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', help: 'The coding identifier for the action.', documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}. $$DOC{ref:'.name'} should generally only contain identifier-safe characters. $$DOC{ref:'.'} names should use camelCase staring with a lower case letter. */} }, { name: 'label', type: 'String', displayWidth: 70, displayHeight: 1, defaultValueFn: function() { return labelize(this.name); }, help: 'The display label for the action.', documentation: function() { /* A human readable label for the $$DOC{ref:'.'}. May contain spaces or other odd characters. */} }, { name: 'speechLabel', type: 'String', displayWidth: 70, displayHeight: 1, defaultValueFn: function() { return this.label; }, help: 'The speech label for the action.', documentation: "A speakable label for the $$DOC{ref:'.'}. Used for accessibility." }, { name: 'help', label: 'Help Text', type: 'String', displayWidth: 70, displayHeight: 6, defaultValue: '', help: 'Help text associated with the action.', documentation: function() { /* This $$DOC{ref:'.help'} text informs end users how to use the $$DOC{ref:'.'}, through field labels or tooltips. */} }, { model_: 'DocumentationProperty', name: 'documentation', documentation: 'The developer documentation.', debug: true }, { name: 'default', type: 'Boolean', view: 'foam.ui.BooleanView', defaultValue: false, help: 'Indicates if this is the default action.', documentation: function() { /* Indicates if this is the default $$DOC{ref:'Action'}. */} }, { model_: 'FunctionProperty', name: 'isAvailable', label: 'Available', displayWidth: 70, displayHeight: 3, defaultValue: function() { return true; }, help: 'Function to determine if action is available.', documentation: function() { /* A function used to determine if the $$DOC{ref:'Action'} is available. */} }, { model_: 'FunctionProperty', name: 'isEnabled', label: 'Enabled', displayWidth: 70, displayHeight: 3, defaultValue: function() { return true; }, help: 'Function to determine if action is enabled.', documentation: function() { /* A function used to determine if the $$DOC{ref:'Action'} is enabled. */} }, { model_: 'FunctionProperty', name: 'labelFn', label: 'Label Function', defaultValue: function(action) { return action.label; }, help: "Function to determine label. Defaults to 'this.label'.", documentation: function() { /* A function used to determine the label. Defaults to $$DOC{ref:'.label'}. */} }, { name: 'iconUrl', type: 'String', defaultValue: undefined, help: 'Provides a url for an icon to render for this action', documentation: function() { /* A url for the icon to render for this $$DOC{ref:'Action'}. */} }, { name: 'showLabel', type: 'String', defaultValue: true, help: 'Property indicating whether the label should be rendered alongside the icon', documentation: function() { /* Indicates whether the $$DOC{ref:'.label'} should be rendered alongside the icon. */} }, { name: 'children', type: 'Array', factory: function() { return []; }, subType: 'Action', view: 'foam.ui.ArrayView', help: 'Child actions of this action.', persistent: false, documentation: function() { /* Child $$DOC{ref:'Action',usePlural:true} of this instance. */} }, { name: 'parent', type: 'String', help: 'The parent action of this action', documentation: function() { /* The parent $$DOC{ref:'Action'} of this instance. */} }, { model_: 'FunctionProperty', name: 'action', displayWidth: 80, displayHeight: 20, defaultValue: '', help: 'Function to implement action.', documentation: function() { /* This function supplies the execution of the $$DOC{ref:'Action'} when triggered. */} }, { model_: 'StringArrayProperty', name: 'keyboardShortcuts', documentation: function() { /* Keyboard shortcuts for the $$DOC{ref:'Action'}. */} }, { name: 'translationHint', label: 'Description for Translation', type: 'String', defaultValue: '' } ], methods: { maybeCall: function(X, that) { /* Executes this action if $$DOC{ref:'.isEnabled'} is allows it. */ if ( this.isAvailable.call(that, this) && this.isEnabled.call(that, this) ) { this.action.call(that, X, this); that.publish(['action', this.name], this); } } } }); //Action.getPrototype().maybeCall = function(X, that) { // if ( this.isEnabled.call(that, this) ) this.action.call(that, X, this); //}; /* Not used yet MODEL({ name: 'Topic', tableProperties: [ 'name', 'description' ], properties: [ { name: 'name', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', // todo: test this preSet: function (newValue) { return newValue.toUpperCase(); }, help: 'The coding identifier for this topic.' }, { name: 'description', type: 'String', displayWidth: 70, displayHeight: 1, defaultValue: '', help: 'A brief description of this topic.' } ] }); */ CLASS({ name: 'Arg', tableProperties: [ 'type', 'name', 'description' ], documentation: function() { /* <p>Represents one $$DOC{ref:'Method'} argument, including the type information.</p> */}, properties: [ { name: 'type', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: 'Object', debug: true, help: 'The type of this argument.', documentation: function() { /* <p>The type of the $$DOC{ref:'.'}, either a primitive type or a $$DOC{ref:'Model'}.</p> */} }, { name: 'javaType', type: 'String', required: false, defaultValueFn: function() { return this.type; }, help: 'The java type that represents the type of this property.', debug: true, documentation: function() { /* When running FOAM in a Java environment, specifies the Java type or class to use. */} }, { name: 'javascriptType', type: 'String', required: false, defaultValueFn: function() { return this.type; }, help: 'The javascript type that represents the type of this property.', debug: true, documentation: function() { /* When running FOAM in a javascript environment, specifies the javascript type to use. */} }, { name: 'name', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', help: 'The coding identifier for the entity.', documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}. $$DOC{ref:'.name'} should generally only contain identifier-safe characters. $$DOC{ref:'.'} names should use camelCase staring with a lower case letter. */} }, { model_: 'BooleanProperty', name: 'required', defaultValue: true, debug: true, documentation: function() { /* Indicates that this arugment is required for calls to the containing $$DOC{ref:'Method'}. */} }, { name: 'defaultValue', help: 'Default Value if not required and not provided.', debug: true, documentation: function() { /* The default value to use if this argument is not required and not provided to the $$DOC{ref:'Method'} call. */} }, { name: 'description', type: 'String', displayWidth: 70, displayHeight: 1, defaultValue: '', help: 'A brief description of this argument.', debug: true, documentation: function() { /* A human-readable description of the argument. */} }, { name: 'help', label: 'Help Text', type: 'String', displayWidth: 70, displayHeight: 6, defaultValue: '', help: 'Help text associated with the entity.', debug: true, documentation: function() { /* This $$DOC{ref:'.help'} text informs end users how to use the $$DOC{ref:'.'}, through field labels or tooltips. */} }, { model_: 'DocumentationProperty', name: 'documentation', documentation: 'The developer documentation.', debug: true } ], methods: { decorateFunction: function(f, i) { if ( this.type === 'Object' ) return f; var type = this.type; return this.required ? function() { console.assert(arguments[i] !== undefined, 'Missing required argument# ' + i); console.assert(typeof arguments[i] === type, 'argument# ' + i + ' type expected to be ' + type + ', but was ' + (typeof arguments[i]) + ': ' + arguments[i]); return f.apply(this, arguments); } : function() { console.assert(arguments[i] === undefined || typeof arguments[i] === type, 'argument# ' + i + ' type expected to be ' + type + ', but was ' + (typeof arguments[i]) + ': ' + arguments[i]); return f.apply(this, arguments); } ; } }, templates:[ { model_: 'Template', name: 'javaSource', description: 'Java Source', template: '<%= this.type %> <%= this.name %>', debug: true }, { model_: 'Template', name: 'closureSource', description: 'Closure JavaScript Source', template: '@param {<%= this.javascriptType %>} <%= this.name %> .', debug: true }, { model_: 'Template', name: 'webIdl', description: 'Web IDL Source', template: '<%= this.type %> <%= this.name %>', debug: true } ] }); CLASS({ name: 'Constant', plural: 'constants', tableProperties: [ 'name', 'value', 'description' ], documentation: function() {/* */}, properties: [ { name: 'name', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', help: 'The coding identifier for the entity.', documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}. $$DOC{ref:'.name'} should generally only contain identifier-safe characters. $$DOC{ref:'.'} names should use camelCase staring with a lower case letter. */} }, { name: 'description', type: 'String', displayWidth: 70, displayHeight: 1, defaultValue: '', help: 'A brief description of this method.', documentation: function() { /* A human readable description of the $$DOC{ref:'.'}. */} }, { model_: 'DocumentationProperty', name: 'documentation', documentation: 'The developer documentation.', debug: true }, { name: 'value', help: 'The value of the constant..' }, { name: 'type', defaultValue: '', help: 'Type of the constant.' }, { name: 'translationHint', label: 'Description for Translation', type: 'String', defaultValue: '' } ] }); CLASS({ name: 'Message', plural: 'messages', tableProperties: [ 'name', 'value', 'translationHint' ], documentation: function() {/* */}, properties: [ { name: 'name', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', help: 'The coding identifier for the message.', documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}. $$DOC{ref:'.name'} should generally only contain identifier-safe characters. $$DOC{ref:'.'} names should use camelCase staring with a lower case letter. */} }, { name: 'value', type: 'String', help: 'The message itself.' }, { name: 'meaning', type: 'String', help: 'Linguistic clarification to resolve ambiguity.', documentation: function() {/* A human readable discussion of the $$DOC{ref:'.'} to resolve linguistic ambiguities. */} }, { model_: 'ArrayProperty', name: 'placeholders', help: 'Placeholders to inject into the message.', documentation: function() {/* Array of plain Javascript objects describing in-message placeholders. The data can be expanded into $$DOC{ref:'foam.i18n.Placeholder'}, for example. */} }, { model_: 'FunctionProperty', name: 'replaceValues', documentation: function() {/* Function that binds values to message contents. */}, defaultValue: function() { return this.value; } }, { name: 'translationHint', type: 'String', displayWidth: 70, displayHeight: 1, defaultValue: '', help: 'A brief description of this message and the context in which it used.', documentation: function() {/* A human readable description of the $$DOC{ref:'.'} and its context for the purpose of translation. */} } ] }); CLASS({ name: 'Method', plural: 'Methods', tableProperties: [ 'name', 'description' ], documentation: function() {/* <p>A $$DOC{ref:'Method'} represents a callable piece of code with $$DOC{ref:'.args',text:'arguments'} and an optional return value. </p> <p>$$DOC{ref:'Method',usePlural:true} contain code that runs in the instance's scope, so code in your $$DOC{ref:'Method'} has access to the other $$DOC{ref:'Property',usePlural:true} and features of your $$DOC{ref:'Model'}.</p> <ul> <li><code>this.propertyName</code> gives the value of a $$DOC{ref:'Property'}</li> <li><code>this.propertyName$</code> is the binding point for the $$DOC{ref:'Property'}. Assignment will bind bi-directionally, or <code>Events.follow(src, dst)</code> will bind from src to dst.</li> <li><code>this.methodName</code> calls another $$DOC{ref:'Method'} of this $$DOC{ref:'Model'}</li> <li><p><code>this.SUPER()</code> calls the $$DOC{ref:'Method'} implementation from the base $$DOC{ref:'Model'} (specified in $$DOC{ref:'Model.extendsModel'}).</p> <ul> <li> <p>Calling <code>this.SUPER()</code> is extremely important in your <code>init()</code> $$DOC{ref:'Method'}, if you provide one.</p> <p>You can also specify <code>SUPER</code> as the first argument of your Javascript function, and it will be populated with the correct base function automatically:</p> <p><code>function(other_arg) {<br/> &nbsp;&nbsp; this.SUPER(other_arg); // calls super, argument is optional depending on what your base method takes.<br/> &nbsp;&nbsp; ...<br/></code> </p> </li> </ul> </li> </ul> */}, properties: [ { name: 'name', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', help: 'The coding identifier for the entity.', documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}. $$DOC{ref:'.name'} should generally only contain identifier-safe characters. $$DOC{ref:'.'} names should use camelCase staring with a lower case letter. */} }, { name: 'description', type: 'String', displayWidth: 70, displayHeight: 1, defaultValue: '', help: 'A brief description of this method.', documentation: function() { /* A human readable description of the $$DOC{ref:'.'}. */} }, { name: 'help', label: 'Help Text', type: 'String', displayWidth: 70, displayHeight: 6, defaultValue: '', debug: true, help: 'Help text associated with the entity.', documentation: function() { /* This $$DOC{ref:'.help'} text informs end users how to use the $$DOC{ref:'.'}, through field labels or tooltips. */} }, { model_: 'DocumentationProperty', name: 'documentation', documentation: 'The developer documentation.', debug: true }, { name: 'code', type: 'Function', displayWidth: 80, displayHeight: 30, view: 'foam.ui.FunctionView', help: 'Javascript code to implement this method.', postSet: function() { if ( ! DEBUG ) return; // check for documentation in a multiline comment at the beginning of the code // accepts "/* comment */ function() {...." or "function() { /* comment */ ..." // TODO: technically unicode letters are valid in javascript identifiers, which we are not catching here for function arguments. var multilineComment = /^\s*function\s*\([\$\s\w\,]*?\)\s*{\s*\/\*([\s\S]*?)\*\/[\s\S]*$|^\s*\/\*([\s\S]*?)\*\/([\s\S]*)/.exec(this.code.toString()); if ( multilineComment ) { var bodyFn = multilineComment[1]; this.documentation = this.Y.Documentation.create({ name: this.name, body: bodyFn }) } }, documentation: function() { /* <p>The code to execute for the $$DOC{ref:'Method'} call.</p> <p>In a special case for javascript documentation, an initial multiline comment, if present, will be pulled from your code and used as a documentation template: <code>function() { \/\* docs here \*\/ code... }</code></p> */} }, { name: 'returnType', defaultValue: '', help: 'Return type.', documentation: function() { /* The return type of the $$DOC{ref:'Method'}. */}, debug: true }, { model_: 'BooleanProperty', name: 'returnTypeRequired', defaultValue: true, documentation: function() { /* Indicates whether the return type is checked. */}, debug: true }, { model_: 'ArrayProperty', name: 'args', type: 'Array[Arg]', subType: 'Arg', view: 'foam.ui.ArrayView', factory: function() { return []; }, defaultValue: [], help: 'Method arguments.', documentation: function() { /* The $$DOC{ref:'Arg',text:'Arguments'} for the method. */}, debug: true }, { name: 'whenIdle', help: 'Should this listener be deferred until the system is idle (ie. not running any animations).', documentation: function() { /* For a listener $$DOC{ref:'Method'}, indicates that the events should be delayed until animations are finished. */} }, { name: 'isMerged', help: 'As a listener, should this be merged?', documentation: function() { /* For a listener $$DOC{ref:'Method'}, indicates that the events should be merged to avoid repeated activations. */} }, { model_: 'BooleanProperty', name: 'isFramed', help: 'As a listener, should this be animated?', defaultValue: false, documentation: function() { /* For a listener $$DOC{ref:'Method'}, indicates that this listener is animated, and events should be merged to trigger only once per frame. */} }, ], templates:[ { model_: 'Template', name: 'javaSource', description: 'Java Source', template: '<%= this.returnType || "void" %> <%= this.name %>(' + '<% for ( var i = 0 ; i < this.args.length ; i++ ) { var arg = this.args[i]; %>' + '<%= arg.javaSource() %><% if ( i < this.args.length-1 ) out(", ");%>' + '<% } %>' + ')' }, { model_: 'Template', name: 'closureSource', description: 'Closure JavaScript Source', // TODO: Change returnType to returnType.javascriptType template: '/**\n' + '<% for ( var i = 0; i < this.args.length ; i++ ) { var arg = this.args[i]; %>' + ' * <%= arg.closureSource() %>\n' + '<% } %>' + '<% if (this.returnType) { %>' + ' * @return {<%= this.returnType %>} .\n' + '<% } %>' + ' */\n' + '<%= arguments[1] %>.prototype.<%= this.name %> = goog.abstractMethod;' }, { model_: 'Template', name: 'webIdl', description: 'Web IDL Source', template: '<%= this.returnType || \'void\' %> <%= this.name %>(' + '<% for ( var i = 0 ; i < this.args.length ; i++ ) { var arg = this.args[i]; %>' + '<%= arg.webIdl() %><% if ( i < this.args.length-1 ) out(", "); %>' + '<% } %>' + ')' } ] }); // initialize to empty object for the two methods added below Method.getPrototype().decorateFunction = function(f) { for ( var i = 0 ; i < this.args.length ; i++ ) { var arg = this.args[i]; f = arg.decorateFunction(f, i); } var returnType = this.returnType; return returnType ? function() { var ret = f.apply(this, arguments); console.assert(typeof ret === returnType, 'return type expected to be ' + returnType + ', but was ' + (typeof ret) + ': ' + ret); return ret; } : f ; }; Method.getPrototype().generateFunction = function() { var f = this.code; return DEBUG ? this.decorateFunction(f) : f; }; Method.methods = { decorateFunction: Method.getPrototype().decorateFunction, generateFunction: Method.getPrototype().generateFunction }; CLASS({ name: 'Template', tableProperties: [ 'name', 'description' ], documentation: function() {/* <p>A $$DOC{ref:'.'} is processed to create a method that generates content for a $$DOC{ref:'foam.ui.View'}. Sub-views can be created from inside the $$DOC{ref:'Template'} using special tags. The content is lazily processed, so the first time you ask for a $$DOC{ref:'Template'} the content is compiled, tags expanded and sub-views created. Generally a template is included in a $$DOC{ref:'foam.ui.View'}, since after compilation a method is created and attached to the $$DOC{ref:'foam.ui.View'} containing the template. </p> <p>For convenience, $$DOC{ref:'Template',usePlural:true} can be specified as a function with a block comment inside to avoid line wrapping problems: <code>templates: [ myTemplate: function() { \/\* my template content \*\/ }]</code> </p> <p>HTML $$DOC{ref:'Template',usePlural:true} can include the following JSP-style tags: </p> <ul> <li><code>&lt;% code %&gt;</code>: code inserted into template, but nothing implicitly output</li> <li><code>&lt;%= comma-separated-values %&gt;</code>: all values are appended to template output</li> <li><code>&lt;%# expression %&gt;</code>: dynamic (auto-updating) expression is output</li> <li><code>\\&lt;new-line&gt;</code>: ignored</li> <li><code>$$DOC{ref:'Template',text:'%%value'}(&lt;whitespace&gt;|{parameters})</code>: output a single value to the template output</li> <li><code>$$DOC{ref:'Template',text:'$$feature'}(&lt;whitespace&gt;|{parameters})</code>: output the View or Action for the current Value</li> <li><code>&lt;!-- comment --&gt;</code> comments are stripped from $$DOC{ref:'Template',usePlural:true}.</li> </ul> */}, properties: [ { name: 'name', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', help: 'The template\'s unique name.', documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}. $$DOC{ref:'.name'} should generally only contain identifier-safe characters. $$DOC{ref:'.'} names should use camelCase staring with a lower case letter. */} }, { name: 'description', type: 'String', required: true, displayWidth: 70, displayHeight: 1, defaultValue: '', help: 'The template\'s description.', documentation: "A human readable description of the $$DOC{ref:'.'}." }, { model_: 'ArrayProperty', name: 'args', type: 'Array[Arg]', subType: 'Arg', view: 'foam.ui.ArrayView', factory: function() { return []; }, defaultValue: [], help: 'Method arguments.', documentation: function() { /* The $$DOC{ref:'Arg',text:'Arguments'} for the $$DOC{ref:'Template'}. */} }, { name: 'template', type: 'String', displayWidth: 180, displayHeight: 30, rows: 30, cols: 80, defaultValue: '', view: 'foam.ui.TextAreaView', // Doesn't work because of bootstrapping issues. // preSet: function(_, t) { return typeof t === 'function' ? multiline(t) : t ; }, help: 'Template text. <%= expr %> or <% out(...); %>', documentation: "The string content of the uncompiled $$DOC{ref:'Template'} body." }, { name: 'futureTemplate', transient: true }, { name: 'code', transient: true }, /* { name: 'templates', type: 'Array[Template]', subType: 'Template', view: 'foam.ui.ArrayView', defaultValue: [], help: 'Sub-templates of this template.' },*/ { model_: 'DocumentationProperty', name: 'documentation', debug: true } ] }); CLASS({ name: 'Documentation', tableProperties: [ 'name' ], documentation: function() {/* <p>The $$DOC{ref:'Documentation'} model is used to store documentation text to describe the use of other models. Set the $$DOC{ref:'Model.documentation'} property of your model and specify the body text:</p> <ul> <li><p>Fully define the Documentation model:</p><p>documentation: { model_: 'Documentation', body: function() { \/\* your doc text \*\/} }</p> </li> <li><p>Define as a function:</p><p>documentation: function() { \/\* your doc text \*\/} </p> </li> <li><p>Define as a one-line string:</p><p>documentation: "your doc text" </p> </li> </ul> */}, properties: [ { name: 'name', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: 'documentation', help: 'The Document\'s unique name.', documentation: "An optional name for the document. Documentation is normally referenced by the name of the containing Model." }, { name: 'label', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', help: 'The Document\'s title or descriptive label.', documentation: "A human readable title to display. Used for books of documentation and chapters." }, { name: 'body', type: 'Template', defaultValue: '', help: 'The main content of the document.', documentation: "The main body text of the document. Any valid template can be used, including the $$DOC{ref:'foam.documentation.DocView'} specific $$DOC{ref:'foam.documentation.DocView',text:'$$DOC{\"ref\"}'} tag.", preSet: function(_, template) { return TemplateUtil.expandTemplate(this, template); } }, { model_: 'ArrayProperty', name: 'chapters', type: 'Array[Document]', subtype: 'Documentation', view: 'foam.ui.ArrayView', factory: function() { return []; }, defaultValue: [], help: 'Sub-documents comprising the full body of this document.', documentation: "Optional sub-documents to be included in this document. A viewer may choose to provide an index or a table of contents.", debug: true, preSet: function(old, nu) { if ( ! DEBUG ) return []; // returning undefined causes problems var self = this; var foamalized = []; // create models if necessary nu.forEach(function(chapter) { if (chapter && typeof self.Y.Documentation != "undefined" && self.Y.Documentation // a source has to exist (otherwise we'll return undefined below) && ( !chapter.model_ // but we don't know if the user set model_ || !chapter.model_.getPrototype // model_ could be a string || !self.Y.Documentation.isInstance(chapter) // check for correct type ) ) { // So in this case we have something in documentation, but it's not of the // "Documentation" model type, so FOAMalize it. if (chapter.body) { foamalized.push(self.Y.Documentation.create( chapter )); } else { foamalized.push(self.Y.Documentation.create({ body: chapter })); } } else { foamalized.push(chapter); } }); return foamalized; }, //postSet: function() { console.log("post ",this.chapters); } } ] }); // HACK to get around property-template bootstrap ordering issues TemplateUtil.expandModelTemplates(Property); TemplateUtil.expandModelTemplates(Method); TemplateUtil.expandModelTemplates(Model); TemplateUtil.expandModelTemplates(Arg); /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ CLASS({ name: 'Interface', plural: 'Interfaces', tableProperties: [ 'package', 'name', 'description' ], documentation: function() { /* <p>$$DOC{ref:'Interface',usePlural:true} specify a set of methods with no implementation. $$DOC{ref:'Model',usePlural:true} implementing $$DOC{ref:'Interface'} fill in the implementation as needed. This is analogous to $$DOC{ref:'Interface',usePlural:true} in object-oriented languages.</p> */}, properties: [ { name: 'id', transient: true, factory: function() { return this.package ? this.package + '.' + this.name : this.name; } }, { name: 'name', required: true, help: 'Interface name.', documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}. $$DOC{ref:'.name'} should generally only contain identifier-safe characters. $$DOC{ref:'.'} definition names should use CamelCase starting with a capital letter. */} }, { name: 'package', help: 'Interface package.', documentation: Model.PACKAGE.documentation }, { name: 'extends', type: 'Array[String]', view: 'foam.ui.StringArrayView', help: 'Interfaces extended by this interface.', documentation: function() { /* The other $$DOC{ref:'Interface',usePlural:true} this $$DOC{ref:'Interface'} inherits from. Like a $$DOC{ref:'Model'} instance can $$DOC{ref:'Model.extendsModel'} other $$DOC{ref:'Model',usePlural:true}, $$DOC{ref:'Interface',usePlural:true} should only extend other instances of $$DOC{ref:'Interface'}.</p> <p>Do not specify <code>extendsModel: 'Interface'</code> unless you are creating a new interfacing system. */} }, { name: 'description', type: 'String', required: true, displayWidth: 70, displayHeight: 1, defaultValue: '', help: 'The interface\'s description.', documentation: function() { /* A human readable description of the $$DOC{ref:'.'}. */ } }, { name: 'help', label: 'Help Text', displayWidth: 70, displayHeight: 6, view: 'foam.ui.TextAreaView', help: 'Help text associated with the argument.', documentation: function() { /* This $$DOC{ref:'.help'} text informs end users how to use the $$DOC{ref:'.'}, through field labels or tooltips. */} }, { model_: 'DocumentationProperty', name: 'documentation', debug: true }, { model_: 'ArrayProperty', name: 'methods', type: 'Array[Method]', subType: 'Method', view: 'foam.ui.ArrayView', factory: function() { return []; }, defaultValue: [], help: 'Methods associated with the interface.', documentation: function() { /* <p>The $$DOC{ref:'Method',usePlural:true} that the interface requires extenders to implement.</p> */} } ], templates:[ { model_: 'Template', name: 'javaSource', description: 'Java Source', template: 'public interface <% out(this.name); %>\n' + '<% if ( this.extends.length ) { %> extends <%= this.extends.join(", ") %>\n<% } %>' + '{\n<% for ( var i = 0 ; i < this.methods.length ; i++ ) { var meth = this.methods[i]; %>' + ' <%= meth.javaSource() %>;\n' + '<% } %>' + '}' }, { model_: 'Template', name: 'closureSource', description: 'Closure JavaScript Source', template: 'goog.provide(\'<%= this.name %>\');\n' + '\n' + '/**\n' + ' * @interface\n' + '<% for ( var i = 0 ; i < this.extends.length ; i++ ) { var ext = this.extends[i]; %>' + ' * @extends {<%= ext %>}\n' + '<% } %>' + ' */\n' + '<%= this.name %> = function() {};\n' + '<% for ( var i = 0 ; i < this.methods.length ; i++ ) { var meth = this.methods[i]; %>' + '\n<%= meth.closureSource(undefined, this.name) %>\n' + '<% } %>' }, { model_: 'Template', name: 'webIdl', description: 'Web IDL Source', template: 'interface <%= this.name %> <% if (this.extends.length) { %>: <%= this.extends[0] %> <% } %>{\n' + '<% for ( var i = 0 ; i < this.methods.length ; i++ ) { var meth = this.methods[i]; %>' + ' <%= meth.webIdl() %>;\n' + '<% } %>' + '}' } ] }); CLASS({ name: 'UnitTest', plural: 'Unit Tests', exports: [ 'log', 'jlog', 'assert', 'fail', 'ok', 'append' ], documentation: function() {/* <p>A basic unit test. $$DOC{ref: ".atest"} is the main method, it executes this test.</p> <p>After the test has finished running, its $$DOC{ref: ".passed"} and $$DOC{ref: ".failed"} properties count the number of assertions that passed and failed in this test <em>subtree</em> (that is, including the children, if run).</p> <p>Test failure is abstracted by the $$DOC{ref: ".hasFailed"} method; this method should always be used, since other subclasses have different definitions of failure.</p> */}, tableProperties: [ 'description', 'passed', 'failed' ], properties: [ { model_: 'Property', name: 'name', type: 'String', required: true, displayWidth: 50, documentation: 'The unit test\'s name.' }, { model_: 'StringProperty', name: 'modelId' }, { model_: 'Property', name: 'description', type: 'String', displayWidth: 70, displayHeight: 5, defaultValue: '', // defaultValueFn: function() { return "Test " + this.name; }, documentation: 'A multi-line description of the unit test.' }, { model_: 'BooleanProperty', name: 'disabled', documentation: 'When true, this test is ignored. Test runners should exclude disabled tests from their DAOs.', defaultValue: false }, { model_: 'IntProperty', name: 'passed', required: true, transient: true, displayWidth: 8, displayHeight: 1, view: 'foam.ui.IntFieldView', documentation: 'Number of assertions which have passed.' }, { model_: 'IntProperty', name: 'failed', required: true, transient: true, displayWidth: 8, displayHeight: 1, documentation: 'Number of assertions which have failed.' }, { model_: 'BooleanProperty', name: 'async', defaultValue: false, documentation: 'Set to make this test asynchronoous. Async tests receive a <tt>ret</tt> parameter as their first argument, and $$DOC{ref: ".atest"} will not return until <tt>ret</tt> is called by the test code.' }, { model_: 'FunctionProperty', name: 'code', label: 'Test Code', displayWidth: 80, displayHeight: 30, documentation: 'The code for the test. Should not include the <tt>function() { ... }</tt>, just the body. Should expect a <tt>ret</tt> parameter when the test is async, see $$DOC{ref: ".async", text: "above"}.', fromElement: function(e, p) { var txt = e.innerHTML; txt = txt.trim().startsWith('function') ? txt : this.async ? 'function(ret) {\n' + txt + '\n}' : 'function() {\n' + txt + '\n}' ; this[p.name] = eval('(' + txt + ')'); }, adapt: function(_, value) { if ( typeof value === 'string' ) { if ( value.startsWith('function') ) { value = eval('(' + value + ')'); } else { value = new Function(value); } } // Now value is a function either way. // We just need to check that if it's async it has an argument. if ( typeof value === 'function' && this.async && value.length === 0 ) { var str = value.toString(); return eval('(function(ret)' + str.substring(str.indexOf('{')) + ')'); } return value; } }, { model_: 'Property', name: 'results', type: 'String', mode: 'read-only', view: 'foam.ui.UnitTestResultView', transient: true, required: true, displayWidth: 80, displayHeight: 20, documentation: 'Log output for this test. Written to by $$DOC{ref: ".log"}, as well as $$DOC{ref: ".assert"} and its friends $$DOC{ref: ".fail"} and $$DOC{ref: ".ok"}.' }, { model_: 'StringArrayProperty', name: 'tags', label: 'Tags', documentation: 'A list of tags for this test. Gives the environment(s) in which a test can be run. Currently in use: node, web.' }, { model_: 'BooleanProperty', name: 'running', defaultValue: false } ], methods:{ atest: function(model) { return function(ret) { var exception = false; try { var obj = model.create(undefined, this.Y); var self = this; this.modelId = model.id; var finished = function() { ret(!self.hasFailed()); }; if ( this.async ) this.code.call(obj, finished); else this.code.call(obj); } catch(e) { this.fail("Exception thrown: " + e.stack); exception = true; ret(false); } if ( ! this.async && ! exception ) finished(); }.bind(this); }, append: function(s) { this.results += s; }, log: function(/*arguments*/) { for ( var i = 0 ; i < arguments.length ; i++ ) this.append(arguments[i]); this.append('\n'); }, jlog: function(/*arguments*/) { for ( var i = 0 ; i < arguments.length ; i++ ) this.append(JSONUtil.stringify(arguments[i])); this.append('\n'); }, addHeader: function(name) { this.log('<tr><th colspan=2 class="resultHeader">' + name + '</th></tr>'); }, assert: function(condition, comment) { if ( condition ) this.passed++; else this.failed++; this.log( (comment ? comment : '(no message)') + ' ' + (condition ? "<font color=green>OK</font>" : "<font color=red>ERROR</font>")); }, fail: function(comment) { this.assert(false, comment); }, ok: function(comment) { this.assert(true, comment); }, hasFailed: function() { return this.failed > 0; } } }); CLASS({ name: 'RegressionTest', label: 'Regression Test', documentation: 'A $$DOC{ref: "UnitTest"} with a "gold master", which is compared with the output of the live test.', extendsModel: 'UnitTest', properties: [ { name: 'master', documentation: 'The "gold" version of the output. Compared with the $$DOC{ref: ".results"} using <tt>.equals()</tt>, and the test passes if they match.' }, { name: 'results', view: 'foam.ui.RegressionTestResultView' }, { model_: 'BooleanProperty', name: 'regression', hidden: true, transient: true, defaultValue: false, documentation: 'Set after $$DOC{ref: ".atest"}: <tt>true</tt> if $$DOC{ref: ".master"} and $$DOC{ref: ".results"} match, <tt>false</tt> if they don\'t.' }, { model_: 'BooleanProperty', name: 'hasRun', defaultValue: false, transient: true } ], methods: { atest: function(model) { // Run SUPER's atest, which returns the unexecuted afunc. var sup = this.SUPER(model); // Now we append a last piece that updates regression based on the results. return aseq( sup, function(ret) { this.regression = ! equals(this.results, this.master); this.hasRun = true; ret(!this.hasFailed()); }.bind(this) ); }, hasFailed: function() { return this.regression; } }, actions: [ { name: 'approve', isEnabled: function() { return this.hasRun }, action: function() { this.regression = this.results; } } ] }); CLASS({ name: 'UITest', label: 'UI Test', extendsModel: 'UnitTest', properties: [ { name: 'results', view: 'foam.ui.UITestResultView' } ] }); CLASS({ name: 'Issue', plural: 'Issues', help: 'An issue describes a question, feature request, or defect.', ids: [ 'id' ], tableProperties: [ 'id', 'severity', 'status', 'summary', 'assignedTo' ], documentation: function() { /* An issue describes a question, feature request, or defect. */}, properties: [ { model_: 'IntProperty', name: 'id', label: 'Issue ID', displayWidth: 12, documentation: function() { /* $$DOC{ref:'Issue'} unique sequence number. */ }, help: 'Issue\'s unique sequence number.' }, { name: 'severity', view: { factory_: 'foam.ui.ChoiceView', choices: [ 'Feature', 'Minor', 'Major', 'Question' ] }, defaultValue: 'String', documentation: function() { /* The severity of the issue. */ }, help: 'The severity of the issue.' }, { name: 'status', type: 'String', required: true, view: { factory_: 'foam.ui.ChoiceView', choices: [ 'Open', 'Accepted', 'Complete', 'Closed' ] }, defaultValue: 'String', documentation: function() { /* The status of the $$DOC{ref:'Issue'}. */ }, help: 'The status of the issue.' }, { model_: 'Property', name: 'summary', type: 'String', required: true, displayWidth: 70, displayHeight: 1, documentation: function() { /* A one line summary of the $$DOC{ref:'Issue'}. */ }, help: 'A one line summary of the issue.' }, { model_: 'Property', name: 'created', type: 'DateTime', required: true, displayWidth: 50, displayHeight: 1, factory: function() { return new Date(); }, documentation: function() { /* When this $$DOC{ref:'Issue'} was created. */ }, help: 'When this issue was created.' }, { model_: 'Property', name: 'createdBy', type: 'String', defaultValue: 'kgr', required: true, displayWidth: 30, displayHeight: 1, documentation: function() { /* Who created the $$DOC{ref:'Issue'}. */ }, help: 'Who created the issue.' }, { model_: 'Property', name: 'assignedTo', type: 'String', defaultValue: 'kgr', displayWidth: 30, displayHeight: 1, documentation: function() { /* Who the $$DOC{ref:'Issue'} is currently assigned to. */ }, help: 'Who the issue is currently assigned to.' }, { model_: 'Property', name: 'notes', displayWidth: 75, displayHeight: 20, view: 'foam.ui.TextAreaView', documentation: function() { /* Notes describing $$DOC{ref:'Issue'}. */ }, help: 'Notes describing issue.' } ] }); /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ CLASS({ name: 'Relationship', tableProperties: [ 'name', 'label', 'relatedModel', 'relatedProperty' ], documentation: function() { /* $$DOC{ref:'Relationship',usePlural:true} indicate a parent-child relation between instances of a $$DOC{ref:'Model'} and some child $$DOC{ref:'Model',usePlural:true}, through the indicated $$DOC{ref:'Property',usePlural:true}. If your $$DOC{ref:'Model',usePlural:true} build a tree structure of instances, they could likely benefit from a declared $$DOC{ref:'Relationship'}. */}, properties: [ { name: 'name', type: 'String', displayWidth: 30, displayHeight: 1, defaultValueFn: function() { return GLOBAL[this.relatedModel] ? GLOBAL[this.relatedModel].plural : ''; }, documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}. $$DOC{ref:'.name'} should generally only contain identifier-safe characters. $$DOC{ref:'.'} names should use camelCase staring with a lower case letter. */}, help: 'The coding identifier for the relationship.' }, { name: 'label', type: 'String', displayWidth: 70, displayHeight: 1, defaultValueFn: function() { return this.name.labelize(); }, documentation: function() { /* A human readable label for the $$DOC{ref:'.'}. May contain spaces or other odd characters. */}, help: 'The display label for the relationship.' }, { name: 'help', label: 'Help Text', type: 'String', displayWidth: 70, displayHeight: 6, defaultValue: '', documentation: function() { /* This $$DOC{ref:'.help'} text informs end users how to use the $$DOC{ref:'.'}, through field labels or tooltips. */}, help: 'Help text associated with the relationship.' }, { model_: 'DocumentationProperty', name: 'documentation', documentation: function() { /* The developer documentation. */} }, { name: 'relatedModel', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', documentation: function() { /* The $$DOC{ref:'Model.name'} of the related $$DOC{ref:'Model'}.*/}, help: 'The name of the related Model.' }, { name: 'relatedProperty', type: 'String', required: true, displayWidth: 30, displayHeight: 1, defaultValue: '', documentation: function() { /* The join $$DOC{ref:'Property'} of the related $$DOC{ref:'Model'}. This is the property that links back to this $$DOC{ref:'Model'} from the other $$DOC{ref:'Model',usePlural:true}. */}, help: 'The join property of the related Model.' } ]/*, methods: { dao: function() { var m = this.X[this.relatedModel]; return this.X[m.name + 'DAO']; }, JOIN: function(sink, opt_where) { var m = this.X[this.relatedModel]; var dao = this.X[m.name + 'DAO'] || this.X[m.plural]; return MAP(JOIN( dao.where(opt_where || TRUE), m.getProperty(this.relatedProperty), []), sink); } }*/ }); (function() { for ( var i = 0 ; i < Model.templates.length ; i++ ) Model.templates[i] = JSONUtil.mapToObj(X, Model.templates[i]); Model.properties = Model.properties; delete Model.instance_.prototype_; Model = Model.create(Model); })(); // Go back over each model so far, assigning the new Model to remove any reference // to the bootstrap Model, then FOAMalize any features that were missed due to // the model for that feature type ("Method", "Documentation", etc.) being // missing previously. This time the preSet for each should be fully operational. function recopyModelFeatures(m) { m.model_ = Model; // the preSet for each of these does the work // m.methods = m.methods; // m.templates = m.templates; m.relationships = m.relationships; m.properties = m.properties; // m.actions = m.actions; // m.listeners = m.listeners; m.models = m.models; if ( DEBUG ) { m.tests = m.tests; m.issues = m.issues; } // check for old bootstrap Property instances if ( m.properties && m.properties[0] && ! Property.isInstance(m.properties[0]) ) { m.properties.forEach(function(p) { if ( p.model_.name === 'Property' ) p.model_ = Property; }); } // keep copies of the updated lists if ( DEBUG ) BootstrapModel.saveDefinition(m); } /* // Update Model in everything we've created so far for ( var id in USED_MODELS ) { recopyModelFeatures(GLOBAL.lookup(id)); } */ recopyModelFeatures(Property); recopyModelFeatures(Model); recopyModelFeatures(Method); recopyModelFeatures(Action); recopyModelFeatures(Template); if ( DEBUG ) { for ( var id in UNUSED_MODELS ) { if ( USED_MODELS[id] ) recopyModelFeatures(GLOBAL.lookup(id)); } } USED_MODELS['Model'] = true; /** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ CLASS({ package: 'foam.core.bootstrap', name: 'OrDAO', properties: [ { name: 'primary', help: 'This is the DAO to look things up in first.' }, { name: 'delegate' } ], methods: { find: function(id, sink) { this.primary.find(id, { put: sink.put.bind(sink), error: function() { this.delegate.find(id, sink); }.bind(this) }); } } }); /** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ MODEL({ package: 'foam.core.bootstrap', name: 'BrowserFileDAO', imports: [ 'document', 'window' ], properties: [ { name: 'pending', factory: function() { return {}; } }, { name: 'preload', factory: function() { return {}; } }, { name: 'rootPath', factory: function() { return this.window.FOAM_BOOT_DIR + '../js/'; } }, 'looking_' ], methods: { toURL_: function(key) { return this.rootPath + key.replace(/\./g, '/') + '.js'; }, find: function(key, sink) { if ( this.preload[key] ) { sink && sink.put && sink.put(this.preload[key]); delete this.preload[key]; return; } if ( this.pending[key] ) { this.pending[key].push(sink); return; } this.pending[key] = [sink]; var tag = this.document.createElement('script'); var looking = key; var onerror = function() { var pending = this.pending[key]; delete this.pending[key]; for ( var i = 0 ; i < pending.length ; i++ ) { pending[i] && pending[i].error && pending[i].error.apply(null, arguments); } tag.remove(); }.bind(this); tag.callback = function(data, latch) { var work = [anop]; var obj = JSONUtil.mapToObj(this.X, data, undefined, work); if ( ! obj ) throw new Error('Failed to decode data: ' + data); if ( looking === obj.id ) looking = null; if ( ! this.pending[obj.id] ) { if ( latch ) { latch(data); } else { // Workaround for legacy apps that include extra models via // additional script tags. this.preload[obj.id] = obj; } return; } aseq.apply(null, work)( function(ret) { var sinks = this.pending[obj.id]; delete this.pending[obj.id]; if ( sinks ) { for ( var i = 0; i < sinks.length ; i++ ) { var sink = sinks[i]; sink && sink.put && sink.put(obj); } } }.bind(this)); }.bind(this); tag.onload = function() { if ( looking != null ) { onerror(); } tag.remove(); }; tag.onerror = onerror; tag.src = this.toURL_(key); this.document.head.appendChild(tag); } } }); /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ CLASS({ package: 'foam.ui', name: 'Window', exports: [ '$$', '$', 'addStyle', 'animate', 'cancelAnimationFrame', 'clearInterval', 'clearTimeout', 'console', 'document', 'dynamic', 'error', 'info', 'installedModels', 'log', 'lookup', 'requestAnimationFrame', 'setInterval', 'setTimeout', 'warn', 'window', 'as FOAMWindow' ], properties: [ { name: 'registeredModels', factory: function() { return {}; } }, { model_: 'StringProperty', name: 'name', defaultValue: 'window' }, { name: 'window', postSet: function(_, w) { // TODO: This would be better if ChromeApp.js added this behaviour // in a SubModel of Window, ie. ChromeAppWindow if ( this.X.subDocument ) this.X.subDocument(w.document); w.X = this.Y; this.document = w.document; } }, { name: 'document' // postSet to reset installedModels? }, { name: 'installedModels', documentation: "Each new Window context introduces a new document and resets installedModels so models will install again in the new document.", factory: function() { return {}; } }, { model_: 'BooleanProperty', name: 'isBackground', defaultValue: false }, { name: 'console', lazyFactory: function() { return this.window.console; } }, ], methods: { lookup: function(key) { var ret = GLOBAL.lookup.call(this.Y, key); // var ret = this.X.lookup(key); if ( ret && ! this.registeredModels[key] ) { // console.log('Registering Model: ', key); this.registeredModels[key] = true; } return ret; }, addStyle: function(css) { if ( ! this.document || ! this.document.createElement ) return; var s = this.document.createElement('style'); s.innerHTML = css; this.document.head.insertBefore( s, this.document.head.firstElementChild); }, log: function() { this.console.log.apply(this.console, arguments); }, warn: function() { this.console.warn.apply(this.console, arguments); }, info: function() { this.console.info.apply(this.console, arguments); }, error: function() { this.console.error.apply(this.console, arguments); }, $: function(id) { return ( this.document.FOAM_OBJECTS && this.document.FOAM_OBJECTS[id] ) ? this.document.FOAM_OBJECTS[id] : this.document.getElementById(id); }, $$: function(cls) { return this.document.getElementsByClassName(cls); }, dynamic: function(fn, opt_fn) { return Events.dynamic(fn, opt_fn, this.Y); }, animate: function(duration, fn, opt_interp, opt_onEnd) { return Movement.animate(duration, fn, opt_interp, opt_onEnd, this.Y); }, setTimeout: function(f, t) { return this.window.setTimeout.apply(this.window, arguments); }, clearTimeout: function(id) { this.window.clearTimeout(id); }, setInterval: function(f, t) { return this.window.setInterval.apply(this.window, arguments); }, clearInterval: function(id) { this.window.clearInterval(id); }, requestAnimationFrame: function(f) { if ( this.isBackground ) return this.setTimeout(f, 16); console.assert( this.window.requestAnimationFrame, 'requestAnimationFrame not defined'); return this.window.requestAnimationFrame(f); }, cancelAnimationFrame: function(id) { if ( this.isBackground ) { this.clearTimeout(id); return; } this.window.cancelAnimationFrame && this.window.cancelAnimationFrame(id); } } }); // Using the existence of 'process' to determine that we're running in Node. (function() { var w = foam.ui.Window.create( { window: window, name: 'DEFAULT WINDOW', isBackground: typeof process === 'object' }, X ); FObject.X = X = w.Y; })(); /** * @license * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ // TODO: standardize on either get()/set() or .value CLASS({ name: 'SimpleValue', properties: [ { name: 'value' } ], methods: { init: function(value) { this.value = value || ""; }, get: function() { return this.value; }, set: function(val) { this.value = val; }, toString: function() { return "SimpleValue(" + this.value + ")"; } } }); CLASS({ name: 'SimpleReadOnlyValue', extendsModel: 'SimpleValue', documentation: "A simple value that can only be set during initialization.", properties: [ { name: 'value', preSet: function(old, nu) { if ( typeof this.instance_.value == 'undefined' ) { return nu; } return old; } } ], methods: { set: function(val) { /* Only allow set once. The first initialized value is the only one. */ if ( typeof this.instance_.value == 'undefined' ) { this.SUPER(val); } }, toString: function() { return "SimpleReadOnlyValue(" + this.value + ")"; } } }); /** * @license * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ var DOM = { /** Instantiate FOAM Objects in a document. **/ init: function(X) { if ( ! X.document.FOAM_OBJECTS ) X.document.FOAM_OBJECTS = {}; var fs = X.document.querySelectorAll('foam'); var models = []; for ( var i = 0 ; i < fs.length ; i++ ) { var e = fs[i]; X.lookup(e.getAttribute('view')); X.lookup(e.getAttribute('model')); if ( e.getAttribute('view') ) models.push(arequire(e.getAttribute('view'))); if ( e.getAttribute('model') ) models.push(arequire(e.getAttribute('model'))); } for ( var key in USED_MODELS ) { models.push(arequire(key)); } atime('DOMInit', aseq(apar.apply(null, models), function(ret) { for ( var i = 0 ; i < fs.length ; i++ ) { var e = fs[i]; // Check that the node is still in the DOM // (It won't be if it was the child of another FOAM tag.) var node = e; var body = X.document.body; while ( node && node !== body ) node = node.parentNode; if ( node ) { this.initElement(e, X, X.document); e.innerHTML = ''; } ret(); } }.bind(this)))(); }, initElementChildren: function(e, X) { var a = []; for ( var i = 0 ; i < e.children.length ; i++ ) { var c = e.children[i]; if ( c.tagName === 'FOAM' ) { a.push(DOM.initElement(c, X)); } } return a; }, /** * opt_document -- if supplied the object's view will be added to the document. **/ initElement: function(e, X, opt_document) { arequire('foam.ui.FoamTagView')(function(t) { foam.ui.FoamTagView.create({ element: e }, X); }); }, setClass: function(e, className, opt_enabled) { var oldClassName = e.className || ''; var enabled = opt_enabled === undefined ? true : opt_enabled; e.className = oldClassName.replace(' ' + className, '').replace(className, ''); if ( enabled ) e.className = e.className + ' ' + className; } }; window && window.addEventListener && window.addEventListener('load', function() { DOM.init(X); }, false); // TODO: document and make non-global /** Convert a style size to an Int. Ex. '10px' to 10. **/ function toNum(p) { return p.replace ? parseInt(p.replace('px','')) : p; }; // TODO(kgr): replace all instances of DomValue with new modelled DOMValue. var DomValue = { DEFAULT_EVENT: 'change', DEFAULT_PROPERTY: 'value', create: function(element, opt_event, opt_property) { if ( ! element ) { throw "Missing Element in DomValue"; } return { __proto__: this, element: element, event: opt_event || this.DEFAULT_EVENT, property: opt_property || this.DEFAULT_PROPERTY }; }, setElement: function ( element ) { this.element = element; }, get: function() { return this.element[this.property]; }, set: function(value) { if ( this.element[this.property] !== value ) this.element[this.property] = value; }, addListener: function(listener) { if ( ! this.event ) return; try { this.element.addEventListener(this.event, listener, false); } catch (x) { } }, removeListener: function(listener) { if ( ! this.event ) return; try { this.element.removeEventListener(this.event, listener, false); } catch (x) { // could be that the element has been removed } }, toString: function() { return "DomValue(" + this.event + ", " + this.property + ")"; } }; CLASS({ name: 'DOMValue', properties: [ { name: 'element', required: true }, { name: 'property', defaultValue: 'value' }, { name: 'event', defaultValue: 'change' }, { name: 'value', postSet: function(_, value) { this.element[this.property] = value; } }, { name: 'firstListener_', defaultValue: true } ], methods: { init: function() { this.SUPER(); this.value = this.element[this.property]; }, get: function() { return this.value; }, set: function(value) { this.value = value; }, addListener: function(listener) { if ( this.firstListener_ ) { if ( this.event ) { this.element.addEventListener( this.event, function() { debugger; /* TODO */ }, false); } this.firstListener_ = false; } this.value$.addListener(listener); }, removeListener: function(listener) { this.value$.removeListener(listener); }, toString: function() { return 'DOMValue(' + this.event + ', ' + this.property + ')'; } } }); /** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ CLASS({ package: 'foam.ui', name: 'FoamTagView', extendsModel: 'foam.ui.View', requires: [ 'foam.html.Element', 'foam.ui.View', 'foam.ui.DetailView' // TODO(kgr): arequire() manually, only if required ], imports: [ 'document' ], properties: [ { name: 'element' }, { name: 'className', defaultValue: 'foam-tag' } ], methods: { init: function() { this.SUPER(); if ( ! this.Element.isInstance(this.element) ) this.install(); }, install: function() { var e = this.element; var models = []; var style = e.getAttribute('style'); var modelName = e.getAttribute('model'); var viewName = e.getAttribute('view'); var onInit = e.getAttribute('oninit'); if ( modelName ) models.push(arequire(modelName, this.X)); if ( viewName ) models.push(arequire(viewName, this.X)); aseq(apar.apply(null, models), function(ret) { if ( ! this.holder() ) return; var model = this.X.lookup(modelName); if ( ! model ) { this.error('Unknown Model: ', modelName); return; } model.getPrototype(); var obj = model.create(null, this.X); obj.fromElement(e); if ( obj.model_.DATA && this.hasOwnProperty('data') ) obj.data = this.data; var view; if ( viewName ) { var viewModel = this.X.lookup(viewName); view = viewModel.create({ model: model, data: obj }, this.X); } else if ( this.X.lookup('foam.ui.BaseView').isInstance(obj) ) { view = obj; } else if ( obj.toView_ ) { view = obj.toView_(); } else { var a = this.element.getAttribute('showActions'); var showActions = ! a || ( a.equalsIC('y') || a.equalsIC('yes') || a.equalsIC('true') || a.equalsIC('t') ); view = this.X.lookup('foam.ui.DetailView').create({ model: model, data: obj, showActions: showActions }, obj.Y); } if ( e.id ) this.document.FOAM_OBJECTS[e.id] = obj; obj.view_ = view; this.holder().outerHTML = view.toHTML(); if ( style ) { view.$.setAttribute('style', style); } view.initHTML(); if ( onInit ) aeval('function() { ' + onInit + ' }')(function(f) { f.call(obj); }); }.bind(this))(); }, holder: function() { // TODO(kgr): Add an outerHTML setter to foam.html.Element instead return this.Element.isInstance(this.element) ? this.$ : this.element; }, error: function(msg) { console.error(msg); this.holder.innerHTML = msg; }, initHTML: function() { this.install(); } } }); /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /** A Canvas View for embedding CView's in. **/ // TODO: add a 'mouse' property which creates and connects a Mouse model. CLASS({ name: 'Canvas', extendsModel: 'foam.ui.View', properties: [ { name: 'background', label: 'Background Color', type: 'String', defaultValue: 'white' }, { name: 'width', type: 'int', defaultValue: 100, postSet: function(_, width) { if ( this.$ ) this.$.width = width; } }, { name: 'height', type: 'int', defaultValue: 100, postSet: function(_, height) { if ( this.$ ) this.$.height = height; } } ], listeners: [ { name: 'paint', isFramed: true, code: function() { if ( ! this.$ ) throw EventService.UNSUBSCRIBE_EXCEPTION; this.erase(); this.paintChildren(); } } ], methods: { toHTML: function() { return '<canvas id="' + this.id + '" width="' + this.width + '" height="' + this.height + '"> </canvas>'; }, initHTML: function() { if ( ! this.$ ) return; this.canvas = this.$.getContext('2d'); }, addChild: function(child) { child.parent = null; // needed because super.addChild() skips childen with parents already this.SUPER(child); try { child.addListener(this.paint); } catch (x) { console.log(x); } return this; }, erase: function() { this.canvas.fillStyle = this.background; this.canvas.fillRect(0, 0, this.width, this.height); }, paintChildren: function() { for ( var i = 0 ; i < this.children.length ; i++ ) { var child = this.children[i]; this.canvas.save(); child.paint(); this.canvas.restore(); } } } }); /** * Abstract Canvas View (CView). * * CView's can also be used as regular (DOM) Views because if you call * toHTML() on them they will create their own 'Canvas' View parent. **/ CLASS({ name: 'CView', label: 'CView', properties: [ { name: 'parent', type: 'CView', hidden: true }, { name: 'x', type: 'int', view: 'foam.ui.IntFieldView', defaultValue: 10 }, { name: 'y', type: 'int', view: 'foam.ui.IntFieldView', defaultValue: 10 }, { name: 'width', type: 'int', view: 'foam.ui.IntFieldView', defaultValue: 10 }, { name: 'height', type: 'int', view: 'foam.ui.IntFieldView', defaultValue: 10 }, { name: 'children', type: 'CView[]', factory: function() { return []; }, hidden: true }, { name: 'background', label: 'Background Color', type: 'String', defaultValue: 'white' }, { name: 'canvas', type: 'Canvas', getter: function() { return this.parent && this.parent.canvas; }, setter: undefined, hidden: true } ], listeners: [ { name: 'resizeParent', code: function(evt) { this.parent.width = this.x + this.width + 1; this.parent.height = this.y + this.height + 2; } } ], methods: { toView_: function() { return this; }, toHTML: function() { // If being added to HTML directly, then needs to create own Canvas as parent. // Calling addChild() will set this.parent = canvas. if ( ! this.parent ) { this.parent = this.X.Canvas.create(); this.x$.addListener(this.resizeParent); this.y$.addListener(this.resizeParent); this.width$.addListener(this.resizeParent); this.height$.addListener(this.resizeParent); this.resizeParent(); } return this.parent.toHTML(); }, initHTML: function() { var self = this; var parent = this.parent; parent.addChild(this); parent.initHTML(); this.X.dynamic( function() { self.background; }, function() { parent.background = self.background; }); }, write: function(document) { document.writeln(this.toHTML()); this.initHTML(); }, addChild: function(child) { this.children.push(child); child.parent = this; return this; }, removeChild: function(child) { this.children.deleteI(child); child.parent = undefined; return this; }, erase: function() { this.canvas.fillStyle = this.background; this.canvas.fillRect(0, 0, this.width, this.height); }, paintChildren: function() { for ( var i = 0 ; i < this.children.length ; i++ ) { var child = this.children[i]; this.canvas.save(); child.paint(); this.canvas.restore(); } }, paintSelf: function() {}, paint: function() { if ( ! this.parent.$ ) return; this.erase(); this.paintSelf(); this.paintChildren(); } } }); CLASS({ name: 'Label', properties: [ { name: 'parent', type: 'CView', hidden: true }, { name: 'text', type: 'String', defaultValue: '' }, { name: 'align', label: 'Alignment', type: 'String', defaultValue: 'start' // values: left, right, center, start, end }, { name: 'font', type: 'String', defaultValue: '' }, { name: 'color', type: 'String', defaultValue: 'black' }, { name: 'x', type: 'int', defaultValue: 100 }, { name: 'y', type: 'int', defaultValue: 100 }, { name: 'maxWidth', label: 'Maximum Width', type: 'int', defaultValue: -1 } ], methods: { paint: function() { var canvas = this.parent.canvas; var oldFont = canvas.font; var oldAlign = canvas.textAlign; if ( this.font ) canvas.font = this.font; canvas.textAlign = this.align; canvas.fillStyle = this.color; canvas.fillText(this.text, this.x, this.y); canvas.font = oldFont; canvas.textAlign = oldAlign; } } }); CLASS({ name: 'Box', extendsModel: 'Label', properties: [ { name: 'background', label: 'Background Color', type: 'String', defaultValue: 'white' }, { name: 'border', label: 'Border Color', type: 'String', defaultValue: 'black' }, { name: 'a', label: 'Angle', type: 'int', defaultValue: 0 }, { name: 'width', type: 'int', defaultValue: 100 }, { name: 'height', type: 'int', defaultValue: 100 } ], methods: { paint: function() { var c = this.parent.canvas; c.save(); if ( this.a ) { c.translate(this.x+this.width/2, this.y+this.height/2); c.rotate(this.a); c.translate(-this.x-this.width/2, -this.y-this.height/2); } c.fillStyle = this.background; c.fillRect(this.x, this.y, this.width, this.height); if ( this.border && this.width && this.height ) { c.strokeStyle = this.border; c.strokeRect(this.x, this.y, this.width, this.height); } var oldFont = c.font; var oldAlign = c.textAlign; if ( this.font ) c.font = this.font; c.textAlign = 'center'; //this.align; c.fillStyle = this.color; c.fillText( this.text, this.x + this.width/2, this.y+this.height/2+10); c.font = oldFont; c.textAlign = oldAlign; var grad = c.createLinearGradient(this.x, this.y, this.x+this.width, this.y+this.height); grad.addColorStop( 0, 'rgba(0,0,0,0.35)'); grad.addColorStop(0.5, 'rgba(0,0,0,0)'); grad.addColorStop( 1, 'rgba(255,255,255,0.45)'); c.fillStyle = grad; c.fillRect(this.x, this.y, this.width, this.height); c.restore(); } } }); CLASS({ name: 'Circle', properties: [ { name: 'parent', type: 'CView', hidden: true }, { name: 'color', type: 'String', defaultValue: 'white' }, { name: 'border', label: 'Border Color', type: 'String', defaultValue: undefined }, { name: 'borderWidth', type: 'int', defaultValue: 1 }, { name: 'alpha', type: 'int', defaultValue: 1 }, { name: 'x', type: 'int', defaultValue: 100 }, { name: 'y', type: 'int', defaultValue: 100 }, { name: 'r', label: 'Radius', type: 'int', defaultValue: 20 } ], methods: { paint3d: function() { var canvas = this.parent.canvas; var radgrad = canvas.createRadialGradient(this.x+this.r/6,this.y+this.r/6,this.r/3,this.x+2,this.y,this.r); radgrad.addColorStop(0, '#a7a7a7'/*'#A7D30C'*/); radgrad.addColorStop(0.9, this.color /*'#019F62'*/); radgrad.addColorStop(1, 'black'); canvas.fillStyle = radgrad;; canvas.beginPath(); canvas.arc(this.x, this.y, this.r, 0, Math.PI*2, true); canvas.closePath(); canvas.fill(); }, paint: function() { var canvas = this.parent.canvas; canvas.save(); canvas.globalAlpha = this.alpha; canvas.fillStyle = this.color; if ( this.border && this.r ) { canvas.lineWidth = this.borderWidth; canvas.strokeStyle = this.border; canvas.beginPath(); canvas.arc(this.x, this.y, this.r, 0, Math.PI*2, true); canvas.closePath(); canvas.stroke(); } if ( this.color ) { canvas.beginPath(); canvas.arc(this.x, this.y, this.r, 0, Math.PI*2, true); canvas.closePath(); canvas.fill(); } canvas.restore(); } } }); CLASS({ name: 'ImageCView', properties: [ { name: 'parent', type: 'CView', hidden: true }, { name: 'alpha', type: 'int', defaultValue: 1 }, { name: 'x', type: 'int', defaultValue: 100 }, { name: 'y', type: 'int', defaultValue: 100 }, { name: 'scale', type: 'int', defaultValue: 1 }, { name: 'src', label: 'Source', type: 'String' } ], methods: { init: function() { this.SUPER(); this.image_ = new Image(); this.image_.src = this.src; }, paint: function() { var c = this.parent.canvas; c.translate(this.x, this.y); c.scale(this.scale, this.scale); c.translate(-this.x, -this.y); c.drawImage(this.image_, this.x, this.y); } } }); CLASS({ name: 'Rectangle', properties: [ { name: 'parent', type: 'CView', hidden: true }, { name: 'color', type: 'String', defaultValue: 'white', }, { name: 'x', type: 'int', defaultValue: 1000 }, { name: 'y', type: 'int', defaultValue: 100 }, { name: 'width', type: 'int', defaultValue: 100 }, { name: 'height', type: 'int', defaultValue: 100 } ], methods: { paint: function() { var canvas = this.parent.canvas; canvas.fillStyle = this.color; canvas.fillRect(this.x, this.y, this.width, this.height); } } }); CLASS({ name: 'ProgressCView', extendsModel: 'CView', properties: [ { name: 'value', type: 'Value', factory: function() { return SimpleValue.create(); }, postSet: function(oldValue, newValue) { oldValue && oldValue.removeListener(this.updateValue); newValue.addListener(this.updateValue); } } ], listeners: [ { name: 'updateValue', code: function() { this.paint(); } } ], methods: { paint: function() { var c = this.canvas; c.fillStyle = '#fff'; c.fillRect(0, 0, 104, 20); c.strokeStyle = '#000'; c.strokeRect(0, 0, 104, 20); c.fillStyle = '#f00'; c.fillRect(2, 2, parseInt(this.value.get()), 16); }, destroy: function( isParentDestroyed ) { this.SUPER(isParentDestroyed); this.value.removeListener(this.listener_); } } }); CLASS({ name: 'Graph', extendsModel: 'CView', properties: [ { name: 'style', type: 'String', defaultValue: 'Line', // TODO: fix the view, it's not storabe view: { factory_: 'foam.ui.ChoiceView', choices: [ 'Bar', 'Line', 'Point' ] } }, { name: 'width', type: 'int', view: 'foam.ui.IntFieldView', defaultValue: 5 }, { name: 'height', type: 'int', view: 'foam.ui.IntFieldView', defaultValue: 5 }, { name: 'graphColor', type: 'String', defaultValue: 'green' }, { name: 'backgroundColor', type: 'String', defaultValue: undefined }, { name: 'lineWidth', type: 'int', defaultValue: 6 }, { name: 'drawShadow', type: 'boolean', defaultValue: true }, { name: 'capColor', type: 'String', defaultValue: '' }, { name: 'axisColor', type: 'String', defaultValue: 'black' }, { name: 'gridColor', type: 'String', defaultValue: undefined }, { name: 'axisSize', type: 'int', defaultValue: 2 }, { name: 'xAxisInterval', type: 'int', defaultValue: 0 }, { name: 'yAxisInterval', type: 'int', defaultValue: 0 }, { name: 'maxValue', label: 'Maximum Value', type: 'float', defaultValue: -1 }, { name: 'data', type: 'Array[float]', factory: function() { return []; } }, { name: 'f', label: 'Data Function', type: 'Function', required: false, displayWidth: 70, displayHeight: 3, view: 'foam.ui.FunctionView', defaultValue: function (x) { return x; }, help: 'The graph\'s data function.' } ], issues: [ { id: 1000, severity: 'Major', status: 'Open', summary: 'Make \'style\' view serializable', created: 'Sun Dec 23 2012 18:14:56 GMT-0500 (EST)', createdBy: 'kgr', assignedTo: 'kgr', notes: 'ChoiceView factory prevents Model from being serializable.' } ], methods: { paintLineData: function(canvas, x, y, xs, w, h, maxValue) { if ( this.graphColor ) { canvas.fillStyle = this.graphColor; canvas.beginPath(); canvas.moveTo(x+xs, y+h-xs); for ( var i = 0 ; i < this.data.length ; i++ ) { var d = this.f(this.data[i]); var lx = x+xs+(i==0?0:w*i/(this.data.length-1)); var ly = this.toY(d, maxValue); canvas.lineTo(lx, ly); } canvas.lineTo(x+this.width-1, y+h-xs); canvas.lineTo(x+xs, y+h-xs); canvas.fill(); } if ( this.capColor ) { if ( this.drawShadow ) { canvas.shadowOffsetX = 0; canvas.shadowOffsetY = 2; canvas.shadowBlur = 2; canvas.shadowColor = "rgba(0, 0, 0, 0.5)"; } canvas.strokeStyle = this.capColor; canvas.lineWidth = this.lineWidth; canvas.lineJoin = 'round'; canvas.beginPath(); for ( var i = 0 ; i < this.data.length ; i++ ) { var d = this.f(this.data[i]); var lx = this.toX(i)+0.5; var ly = this.toY(d, maxValue)/*+0.5*/-5; if ( i == 0 ) canvas.moveTo(lx, ly); else canvas.lineTo(lx, ly); } canvas.stroke(); } }, paintPointData: function(canvas, x, y, xs, w, h, maxValue) { canvas.shadowOffsetX = 2; canvas.shadowOffsetY = 2; canvas.shadowBlur = 2; canvas.shadowColor = "rgba(0, 0, 0, 0.5)"; canvas.strokeStyle = this.capColor; canvas.lineWidth = 2; canvas.lineJoin = 'round'; canvas.beginPath(); for ( var i = 0 ; i < this.data.length ; i++ ) { var d = this.f(this.data[i]); var lx = this.toX(i)+0.5; var ly = this.toY(d, maxValue)+0.5; if ( i == 0 ) canvas.moveTo(lx, ly); else canvas.lineTo(lx, ly); } canvas.stroke(); canvas.lineWidth = 3; for ( var i = 0 ; i < this.data.length ; i++ ) { var d = this.f(this.data[i]); var lx = this.toX(i)+0.5; var ly = this.toY(d, maxValue)+0.5; canvas.beginPath(); canvas.arc(lx,ly,4,0,-Math.PI/2); canvas.closePath(); canvas.stroke(); } }, paintBarData: function(canvas, x, y, xs, w, h, maxValue) { canvas.fillStyle = this.graphColor; for ( var i = 0 ; i < this.data.length ; i++ ) { var d = this.f(this.data[i]); var x1 = x+xs+w*i/this.data.length; var y1 = this.toY(d, maxValue); canvas.fillRect(x1, y1, w/this.data.length+1.5, d*h/maxValue); } }, paint: function() { var canvas = this.canvas; var x = this.x; var y = this.y; var xs = this.axisSize; var w = this.width-xs; var h = this.height-xs; var maxValue = this.maxValue; if ( this.backgroundColor ) { canvas.fillStyle = this.backgroundColor; canvas.fillRect(x,y,w,h); } if ( maxValue == -1 ) { maxValue = 0.001; for ( var i = 0 ; i < this.data.length ; i++ ) { var d = this.f(this.data[i]); maxValue = Math.max(maxValue, d); } } if ( this.style == 'Line' ) this.paintLineData(canvas, x, y, xs, w, h, maxValue); else if ( this.style == 'Bar' ) this.paintBarData(canvas, x, y, xs, w, h, maxValue); else if ( this.style == 'Point' ) this.paintPointData(canvas, x, y, xs, w, h, maxValue); if ( this.axisColor && xs != 0 ) { canvas.fillStyle = this.axisColor; // x-axis canvas.fillRect(x, y+h-xs*1.5, this.width, xs); // y-axis canvas.fillRect(x, y, xs, this.height-xs*1.5); } if ( this.xAxisInterval ) { for ( var i = this.xAxisInterval ; i <= this.data.length ; i += this.xAxisInterval ) { var x2 = this.toX(i); if ( this.gridColor ) { canvas.save(); canvas.shadowOffsetX = 0; canvas.shadowOffsetY = 0; canvas.shadowBlur = 0; canvas.fillStyle = this.gridColor; canvas.fillRect(x2+1.5, this.toY(0,1)-2*xs, 0.5, -this.height); canvas.restore(); } canvas.fillRect(x2, this.toY(0,1)-2*xs, xs/2, -xs); } } if ( this.yAxisInterval ) { for ( var i = this.yAxisInterval ; i <= maxValue ; i += this.yAxisInterval ) { var y = this.toY(i, maxValue); if ( this.gridColor ) { canvas.save(); canvas.shadowOffsetX = 0; canvas.shadowOffsetY = 0; canvas.shadowBlur = 0; canvas.fillStyle = this.gridColor; canvas.fillRect(x+xs, y+3, this.width, 0.5); canvas.restore(); } canvas.fillRect(x+xs, y, xs, xs/2); } } }, toX: function(val) { var w = this.width - this.axisSize; return this.x+this.axisSize+(val==0?0:w*val/(this.data.length-1)); }, toY: function(val, maxValue) { var h = this.height - this.axisSize; return this.y+h-val*h/maxValue+0.5; }, lastValue: function() { return this.data[this.data.length-1]; }, addData: function(value, opt_maxNumValues) { var maxNumValues = opt_maxNumValues || this.width; if ( this.data.length == maxNumValues ) this.data.shift(); this.data.push(value); }, watch: function(value, opt_maxNumValues) { var graph = this; value.addListener(function() { graph.addData(value.get(), opt_maxNumValues); }); } } }); var WarpedCanvas = { create: function(c, mx, my, w, h, mag) { return { __proto__: c, warp: function(x, y) { if ( Math.abs(mag) < 0.01 || ( mx < 1 && my < 1 ) ) { this.x = x; this.y = y; return; } var dx = x-mx; var dy = y-my; var r = Math.sqrt(dx*dx + dy*dy); var t = Math.atan2(dy, dx); var R = 400 * (1+mag); r = r/R; if ( r < 1 ) r += mag*3*r*Math.pow(1-r, 4); r = r*R; this.x = mx + Math.cos(t) * r; this.y = my + Math.sin(t) * r; }, moveTo: function(x, y) { this.warp(x, y); c.moveTo(this.x, this.y); this.pX = x; this.pY = y; }, lineTo: function(x2, y2) { var N = 100; var x1 = this.pX; var y1 = this.pY; var dx = (x2 - x1)/N; var dy = (y2 - y1)/N; var x = x1, y = y1; for ( var i = 0 ; i < N ; i++ ) { x += dx; y += dy; this.warp(x, y); c.lineTo(this.x, this.y); } this.pX = x2; this.pY = y2; }, line: function(x1, y1, x2, y2) { c.beginPath(); this.moveTo(x1, y1); this.lineTo(x2, y2); c.stroke(); }, fillText: function(t, x, y) { this.warp(x, y); c.fillText(t, this.x, this.y); }, fillRect: function(x, y, width, height) { c.beginPath(); this.moveTo(x, y); this.lineTo(x+width, y); this.lineTo(x+width, y+height); this.lineTo(x, y+height); this.lineTo(x, y); c.closePath(); c.fill(); }, get font() { return c.linewidth; }, set font(v) { c.linewidth = v; }, get lineWidth() { return c.linewidth; }, set lineWidth(v) { c.linewidth = v; }, get strokeStyle() { return c.strokeStyle; }, set strokeStyle(v) { c.strokeStyle = v; }, get fillStyle() { return c.fillStyle; }, set fillStyle(v) { c.fillStyle = v; }, get textAlign() { return c.textAlign; }, set textAlign(v) { c.textAlign = v; } }; } }; CLASS({ name: 'GridCView', extendsModel: 'CView', label: 'GridCView', requires: ['foam.input.Mouse'], properties: [ { name: 'grid', type: 'GridByExpr', }, { name: 'mag', help: 'The current magnification level. Animates to desiredMag.', defaultValue: 0.6 }, { name: 'desiredMag', postSet: function(_, mag) { this.mag = mag; }, defaultValue: 0.6 }, { name: 'mouse', factory: function() { return this.Mouse.create(); } } ], listeners: [ { name: 'onMouseMove', code: function(evt) { this.parent.paint() } } ], methods: { initHTML: function() { var self = this; this.SUPER(); this.mouse.connect(this.parent.$); this.parent.$.addEventListener('mouseout', function() { this.animation_ && this.animation_(); this.animation_ = Movement.animate( 800, function() { self.mag = 0; }, Movement.oscillate(0.8, self.mag/4))(); }); this.parent.$.addEventListener('mouseenter', function() { this.animation_ && this.animation_(); this.animation_ = Movement.animate( 400, function() { self.mag = self.desiredMag; })(); }); this.parent.$.onmousewheel = function(e) { if ( e.wheelDeltaY > 0 ) { this.desiredMag += 0.05; } else { this.desiredMag = Math.max(0, this.desiredMag-0.05); } this.parent.paint(); }.bind(this); this.mouse.addListener(this.onMouseMove); }, // TODO: move to CView line: function(x1, y1, x2, y2) { var c = this.canvas; c.beginPath(); c.moveTo(x1, y1); c.lineTo(x2, y2); c.closePath(); c.stroke(); }, paint: function() { var ROW_LABEL_WIDTH = 140; var COL_LABEL_HEIGHT = 30; this.width = this.parent.$.parentElement.clientWidth; this.height = this.parent.$.parentElement.clientHeight; var c = this.canvas; var g = this.grid; var cols = g.cols.groups; var rows = g.rows.groups; var sortedCols = g.sortedCols(); var sortedRows = g.sortedRows(); var w = this.width; var h = this.height; var wc = WarpedCanvas.create(c, this.mouse.x, this.mouse.y, w, h, this.mag); var xw = (w-ROW_LABEL_WIDTH) / sortedCols.length; var yw = (h-COL_LABEL_HEIGHT) / sortedRows.length; wc.fillStyle = '#eee'; wc.fillRect(0, 0, this.width, COL_LABEL_HEIGHT); wc.fillRect(0, 0, ROW_LABEL_WIDTH, this.height); wc.lineWidth = 1; wc.strokeStyle = '#000'; wc.fillStyle = '#000'; wc.textAlign = 'left'; wc.font = 'bold 10px arial'; // Vertical Grid Lines for ( var i = 0 ; i < sortedCols.length ; i++ ) { var x = ROW_LABEL_WIDTH + i * xw; wc.fillText(sortedCols[i], x+2, COL_LABEL_HEIGHT/2+2); wc.line(x, 0, x, h); } // First line wc.line(0, 0, 0, h); // Last line wc.line(w, 0, w, h); // Horizontal Grid Lines for ( var i = 0 ; i < sortedRows.length ; i++ ) { var y = COL_LABEL_HEIGHT + i * yw; wc.fillText(sortedRows[i], 5, y + yw/2); wc.line(0, y, w, y); } // First line wc.line(0, 0, w, 0); // Last line wc.line(0, h, w, h); function wdist(x1, y1, x2, y2) { wc.warp(x2, y2); var dx = x1-wc.x; var dy = y1-wc.y; return dx*dx + dy*dy; } for ( var j = 0 ; j < sortedRows.length ; j++ ) { var y = sortedRows[j]; for ( var i = 0 ; i < sortedCols.length ; i++ ) { var x = sortedCols[i]; var value = rows[y].groups[x]; if ( value && value.toCView ) { var cv = value.toCView(); var cx = ROW_LABEL_WIDTH + xw * (i+0.5); var cy = COL_LABEL_HEIGHT + yw * (j+0.5); wc.warp(cx, cy); cv.x = wc.x; cv.y = wc.y; cv.r = Math.sqrt(Math.min( wdist(cv.x, cv.y, cx+xw/2, cy), wdist(cv.x, cv.y, cx-xw/2, cy), wdist(cv.x, cv.y, cx, cy+yw/2), wdist(cv.x, cv.y, cx, cy-yw/2)))-4; cv.x -= cv.r; cv.y -= cv.r; cv.parent = this.parent; if ( cv.r > 3 ) cv.paint(); } } } } } }); /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /** * A sub-set of the DOM Element interface that we use for FOAM tag parsing. * This lets us transparently build FOAM objects and views from either real DOM * or from the output of FOAM's HTML parser. **/ CLASS({ package: 'foam.html', name: 'Element', constants: { OPTIONAL_CLOSE_TAGS: { HTML: true, HEAD: true, BODY: true, P: true, DT: true, DD: true, LI: true, OPTION: true, THEAD: true, TH: true, TBODY: true, TR: true, TD: true, TFOOT: true, COLGROUP: true, }, ILLEGAL_CLOSE_TAGS: { IMG: true, INPUT: true, BR: true, HR: true, FRAME: true, AREA: true, BASE: true, BASEFONT: true, COL: true, ISINDEX: true, LINK: true, META: true, PARAM: true } }, properties: [ { name: 'id' }, { name: 'nodeName'/*, preSet: function(_, v) { return v.toLowerCase(); }*/ }, { name: 'attributeMap_', transient: true, factory: function() { return {}; } }, { name: 'attributes', factory: function() { return []; }, postSet: function(_, attrs) { for ( var i = 0 ; i < attrs.length ; i++ ) this.attributeMap_[attrs[i].name] = attrs[i]; } }, { name: 'childNodes', factory: function() { return []; } }, { name: 'children', transient: true, getter: function() { return this.childNodes.filter(function(c) { return typeof c !== 'string'; }); } }, { name: 'outerHTML', transient: true, getter: function() { var out = '<' + this.nodeName; if ( this.id ) out += ' id="' + this.id + '"'; for ( key in this.attributeMap_ ) { var value = this.attributeMap_[key].value; out += value == undefined ? ' ' + key : ' ' + key + '="' + this.attributeMap_[key].value + '"'; } if ( ! this.ILLEGAL_CLOSE_TAGS[this.nodeName] && ( ! this.OPTIONAL_CLOSE_TAGS[this.nodeName] || this.childNodes.length ) ) { out += '>'; out += this.innerHTML; out += '</' + this.nodeName; } out += '>'; return out; } }, { name: 'innerHTML', transient: true, getter: function() { var out = ''; for ( var i = 0 ; i < this.childNodes.length ; i++ ) out += this.childNodes[i].toString(); return out; } } ], methods: { setAttribute: function(name, value) { var attr = this.getAttributeNode(name); if ( attr ) { attr.value = value; } else { attr = {name: name, value: value}; this.attributes.push(attr); this.attributeMap_[name] = attr; } }, getAttributeNode: function(name) { return this.attributeMap_[name]; }, getAttribute: function(name) { var attr = this.getAttributeNode(name); return attr && attr.value; }, appendChild: function(c) { this.childNodes.push(c); }, removeChild: function(c) { for ( var i = 0; i < this.childNodes.length; ++i ) { if ( this.childNodes[i] === c ) { this.childNodes.splice(i, 1); break; } } }, toString: function() { return this.outerHTML; } } }); var HTMLParser = { __proto__: grammar, create: function() { return { __proto__: this, stack: [ X.foam.html.Element.create({nodeName: 'html'}) ] } }, peek: function() { return this.stack[this.stack.length-1]; }, START: sym('html'), // Use simpleAlt() because endTag() doesn't always look ahead and will // break the regular alt(). html: repeat0(sym('htmlPart')), htmlPart: simpleAlt( sym('cdata'), sym('comment'), sym('text'), sym('endTag'), sym('startTag')), tag: seq( sym('startTag'), repeat(seq1(1, sym('matchingHTML'), sym('htmlPart')))), matchingHTML: function(ps) { return this.stack.length > 1 ? ps : null; }, startTag: seq( '<', sym('tagName'), sym('whitespace'), sym('attributes'), sym('whitespace'), optional('/'), '>'), endTag: (function() { var endTag_ = sym('endTag_'); return function(ps) { return this.stack.length > 1 ? this.parse(endTag_, ps) : undefined; }; })(), endTag_: seq1(1, '</', sym('tagName'), '>'), cdata: seq1(1, '<![CDATA[', str(repeat(not(']]>', anyChar))), ']]>'), comment: seq('<!--', repeat0(not('-->', anyChar)), '-->'), attributes: repeat(sym('attribute'), sym('whitespace')), label: str(plus(notChars(' =/\t\r\n<>\'"'))), tagName: sym('label'), text: str(plus(alt('<%', notChar('<')))), attribute: seq(sym('label'), optional(seq1(1, '=', sym('value')))), value: str(alt( plus(alt(range('a','z'), range('A', 'Z'), range('0', '9'))), seq1(1, '"', repeat(notChar('"')), '"') )), whitespace: repeat0(alt(' ', '\t', '\r', '\n')) }.addActions({ START: function(xs) { // TODO(kgr): I think that this might be a bug if we get a failed compile then // we might not reset state properly. var ret = this.stack[0]; this.stack = [ X.foam.html.Element.create({nodeName: 'html'}) ]; return ret; }, tag: function(xs) { var ret = this.stack[0]; this.stack = [ X.foam.html.Element.create({nodeName: 'html'}) ]; return ret.childNodes[0]; }, attribute: function(xs) { return { name: xs[0], value: xs[1] }; }, cdata: function(xs) { this.peek() && this.peek().appendChild(xs); }, text: function(xs) { this.peek() && this.peek().appendChild(xs); }, startTag: function(xs) { var tag = xs[1]; // < tagName ws attributes ws / > // 0 1 2 3 4 5 6 var obj = X.foam.html.Element.create({nodeName: tag, attributes: xs[3]}); this.peek() && this.peek().appendChild(obj); if ( xs[5] != '/' ) this.stack.push(obj); return obj; }, endTag: function(tag) { var stack = this.stack; while ( stack.length > 1 ) { if ( this.peek().nodeName === tag ) { stack.pop(); return; } var top = stack.pop(); this.peek().childNodes = this.peek().childNodes.concat(top.childNodes); top.childNodes = []; } } }); /* // TODO: move tests to UnitTests function test(html) { console.log('\n\nparsing: ', html); var p = HTMLParser.create(); var res = p.parseString(html); if ( res ) { console.log('Result: ', res.toString()); } else { console.log('error'); } } test('<ba>foo</ba>'); test('<p>'); test('foo'); test('foo bar'); test('foo</end>'); test('<b>foo</b></foam>'); test('<pA a="1">foo</pA>'); test('<pA a="1" b="2">foo<b>bold</b></pA>'); */ (function() { var registry = { }; X.registerElement = function(name, model) { // console.log('registerElement: ', name); registry[name] = model; TemplateParser.foamTag_ = (function() { var start = seq( '<', simpleAlt.apply(null, Object.keys(registry). sort(function(o1, o2) { return o2.compareTo(o1); }). map(function(k) { return literal_ic(k); })), alt('/', ' ', '>')); var html = HTMLParser.create().export('tag'); return function(ps) { var res = this.parse(start, ps) && this.parse(html, ps); if ( ! res ) return null; var elem = res.value; var model = registry[elem.nodeName]; if ( model ) elem.setAttribute('model', model); return res.setValue(elem); }; })(); invalidateParsers(); }; X.elementModel = function(name) { return registry[name]; }; })(); X.registerElement('foam', null); /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ // TODO: add type-checking in partialEval // (type-checking is a subset of partial-eval) function compile_(a) { return /*Expr.isInstance(a) || Property.isInstance(a)*/ a.f ? a : a === true ? TRUE : a === false ? FALSE : ConstantExpr.create({arg1:a}); } function compileArray_(args) { var b = []; for ( var i = 0 ; i < args.length ; i++ ) { var a = args[i]; if ( a !== null && a !== undefined ) b.push(compile_(a)); } return b; } CLASS({ name: 'Expr', documentation: 'Parent model for all mLang expressions. Contains default implementations for many methods.', methods: [ function toMQL() { /* Outputs MQL for this expression. */ return this.label_; }, function toSQL() { /* Outputs SQL for this expression. */ return this.label_; }, function toBQL() { /* Outputs yet another query language for this expression. */ return this.label_; }, function toString() { /* Converts to a string form for debugging; defaults to $$DOC{ref: ".toMQL", text: "MQL"}. */ return this.toMQL(); }, function collectInputs(terms) { /* Recursively adds all inputs of an expression to an array. */ terms.push(this); }, function partialEval() { /* <p>Simplifies the expression by eliminating unnecessary clauses and combining others.</p> <p>Can sometimes reduce whole (sub)expressions to TRUE or FALSE.</p> */ return this; }, function minterm(index, term) { // True if this bit is set in the minterm number. return !!((term >>> index[0]--) & 1 ); }, function normalize() { return this; // Each input term to the expression. var inputs = []; this.collectInputs(inputs); // Truth table for every minterm (combination of inputs). var minterms = new Array(Math.pow(2, inputs.length)); for ( var i = 0; i < minterms.length; i++ ) { minterms[i] = this.minterm([inputs.length - 1], i); } // TODO: Calculate prime implicants and reduce to minimal set. var terms = []; for ( i = 0; i < minterms.length; i++ ) { if ( minterms[i] ) { var subterms = []; for ( var j = 0; j < inputs.length; j++ ) { if ( i & (1 << (inputs.length - j - 1))) subterms.push(inputs[j]); } terms.push(AndExpr.create({ args: subterms })); } } var ret = OrExpr.create({ args: terms }).partialEval(); console.log(this.toMQL(),' normalize-> ', ret.toMQL()); return ret; }, function pipe(sink) { /* Returns a $$DOC{ref: "Sink"} which applies this expression to every value <tt>put</tt> or <tt>remove</tt>d, calling the provided <tt>sink</tt> only for those values which match the expression. */ var expr = this; return { __proto__: sink, put: function(obj) { if ( expr.f(obj) ) sink.put(obj); }, remove: function(obj) { if ( expr.f(obj) ) sink.remove(obj); } }; } ] }); var TRUE = (FOAM({ model_: 'Model', name: 'TrueExpr', extendsModel: 'Expr', documentation: 'Model for the primitive true value.', methods: { clone: function() { return this; }, deepClone: function() { return this; }, toString: function() { return '<true>'; }, toSQL: function() { return '( 1 = 1 )'; }, toMQL: function() { return ''; }, toBQL: function() { return ''; }, f: function() { return true; } } })).create(); var FALSE = (FOAM({ model_: 'Model', name: 'FalseExpr', extendsModel: 'Expr', documentation: 'Model for the primitive false value.', methods: { clone: function() { return this; }, deepClone: function() { return this; }, toSQL: function(out) { return '( 1 <> 1 )'; }, toMQL: function(out) { return '<false>'; }, toBQL: function(out) { return '<false>'; }, f: function() { return false; } } })).create(); var IDENTITY = (FOAM({ model_: 'Model', name: 'IdentityExpr', extendsModel: 'Expr', documentation: 'The identity expression, which passes through its input unchanged.', methods: { clone: function() { return this; }, deepClone: function() { return this; }, f: function(obj) { return obj; }, toString: function() { return 'IDENTITY'; } } })).create(); /** An n-ary function. **/ CLASS({ name: 'NARY', extendsModel: 'Expr', abstract: true, documentation: 'Parent model for expressions which take an arbitrary number of arguments.', properties: [ { name: 'args', label: 'Arguments', type: 'Expr[]', help: 'Sub-expressions', documentation: 'An array of subexpressions which are the arguments to this n-ary expression.', factory: function() { return []; } } ], methods: { toString: function() { var s = this.name_ + '('; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; s += a.toString(); if ( i < this.args.length-1 ) s += (', '); } return s + ')'; }, toSQL: function() { var s; s = this.model_.label; s += '('; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; s += a.toSQL(); if ( i < this.args.length-1 ) out.push(','); } s += ')'; return s; }, toMQL: function() { var s; s = this.model_.label; s += '('; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; s += a.toMQL(); if ( i < this.args.length-1 ) out.push(','); } s += ')'; return str; }, toBQL: function() { var s; s = this.model_.label; s += '('; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; s += a.toBQL(); if ( i < this.args.length-1 ) out.push(','); } s += ')'; return str; } } }); // Allow Singleton mLang's to be desearialized to properly. var TrueExpr = { finished__: true, arequire: function(ret) { return afuture().set(this).get; }, create: function() { return TRUE; } }; var FalseExpr = { finished__: true, arequire: function(ret) { return afuture().set(this).get; }, create: function() { return FALSE; } }; var IdentityExpr = { finished__: true, arequire: function(ret) { return afuture().set(this).get; }, create: function() { return IDENTITY; } }; /** An unary function. **/ CLASS({ name: 'UNARY', extendsModel: 'Expr', abstract: true, documentation: 'Parent model for one-argument expressions.', properties: [ { name: 'arg1', label: 'Argument', type: 'Expr', help: 'Sub-expression', documentation: 'The first argument to the expression.', defaultValue: TRUE } ], methods: { toSQL: function() { return this.label_ + '(' + this.arg1.toSQL() + ')'; }, toMQL: function() { return this.label_ + '(' + this.arg1.toMQL() + ')'; }, toBQL: function() { return this.label_ + '(' + this.arg1.toBQL() + ')'; } } }); /** An unary function. **/ CLASS({ name: 'BINARY', extendsModel: 'UNARY', abstract: true, documentation: 'Parent model for two-argument expressions. Extends $$DOC{ref: "UNARY"} to include $$DOC{ref: ".arg2"}.', properties: [ { name: 'arg2', label: 'Argument', type: 'Expr', help: 'Sub-expression', documentation: 'Second argument to the expression.', defaultValue: TRUE } ], methods: { toSQL: function() { return this.arg1.toSQL() + ' ' + this.label_ + ' ' + this.arg2.toSQL(); }, toMQL: function() { return this.arg1.toMQL() + ' ' + this.label_ + ' ' + this.arg2.toMQL(); }, toBQL: function() { return this.arg1.toBQL() + ' ' + this.label_ + ' ' + this.arg2.toBQL(); } } }); CLASS({ name: 'CountExpr', extendsModel: 'Expr', properties: [ { name: 'count', type: 'int', defaultValue: 0 } ], methods: { reduce: function(other) { return CountExpr.create({count: this.count + other.count}); }, reduceI: function(other) { this.count = this.count + other.count; }, pipe: function(sink) { sink.put(this); }, put: function(obj) { this.count++; }, remove: function(obj) { this.count--; }, toString: function() { return this.count; } } }); function COUNT() { return CountExpr.create(); } CLASS({ name: 'EqExpr', extendsModel: 'BINARY', abstract: true, documentation: function() { /* <p>Binary expression that compares its arguments for equality.</p> <p>When evaluated in Javascript, uses <tt>==</tt>.</p> <p>If the first argument is an array, returns true if any of its value match the second argument.</p> */}, methods: { toSQL: function() { return this.arg1.toSQL() + '=' + this.arg2.toSQL(); }, toMQL: function() { if ( ! this.arg1.toMQL || ! this.arg2.toMQL ) return ''; return this.arg2 === TRUE ? 'is:' + this.arg1.toMQL() : this.arg2.f() == '' ? '-has:' + this.arg1.toMQL() : this.arg1.toMQL() + '=' + this.arg2.toMQL() ; }, toBQL: function() { if ( ! this.arg1.toBQL || ! this.arg2.toBQL ) return ''; return this.arg2 === TRUE ? this.arg1.toBQL() + ':true' : this.arg1.toBQL() + ':' + this.arg2.toBQL() ; }, partialEval: function() { var newArg1 = this.arg1.partialEval(); var newArg2 = this.arg2.partialEval(); if ( ConstantExpr.isInstance(newArg1) && ConstantExpr.isInstance(newArg2) ) { return compile_(newArg1.f() == newArg2.f()); } return this.arg1 !== newArg1 || this.arg2 !== newArg2 ? EqExpr.create({arg1: newArg1, arg2: newArg2}) : this; }, f: function(obj) { var arg1 = this.arg1.f(obj); var arg2 = this.arg2.f(obj); if ( Array.isArray(arg1) ) { return arg1.some(function(arg) { return arg == arg2; }); } if ( arg2 === TRUE ) return !! arg1; if ( arg2 === FALSE ) return ! arg1; return arg1 == arg2; } } }); function EQ(arg1, arg2) { var eq = EqExpr.create(); eq.instance_.arg1 = compile_(arg1); eq.instance_.arg2 = compile_(arg2); return eq; // return EqExpr.create({arg1: compile_(arg1), arg2: compile_(arg2)}); } CLASS({ name: 'ConstantExpr', extendsModel: 'UNARY', methods: { escapeSQLString: function(str) { return "'" + str.replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "'"; }, escapeMQLString: function(str) { if ( str.length > 0 && str.indexOf(' ') == -1 && str.indexOf('"') == -1 && str.indexOf(',') == -1 ) return str; return '"' + str.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"'; }, toSQL: function() { return ( typeof this.arg1 === 'string' ) ? this.escapeSQLString(this.arg1) : this.arg1.toString() ; }, toMQL: function() { return ( typeof this.arg1 === 'string' ) ? this.escapeMQLString(this.arg1) : (this.arg1.toMQL ? this.arg1.toMQL() : this.arg1.toString()); }, toBQL: function() { return ( typeof this.arg1 === 'string' ) ? this.escapeMQLString(this.arg1) : (this.arg1.toBQL ? this.arg1.toBQL() : this.arg1.toString()); }, f: function(obj) { return this.arg1; } } }); CLASS({ name: 'AndExpr', extendsModel: 'NARY', abstract: true, documentation: 'N-ary expression which is true only if each of its 0 or more arguments is true. AND() === TRUE', methods: { // AND has a higher precedence than OR so doesn't need parenthesis toSQL: function() { var s = ''; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; s += a.toSQL(); if ( i < this.args.length-1 ) s += (' AND '); } return s; }, toMQL: function() { var s = ''; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; var sub = a.toMQL(); if ( OrExpr.isInstance(a) ) { sub = '(' + sub + ')'; } s += sub; if ( i < this.args.length-1 ) s += (' '); } return s; }, toBQL: function() { var s = ''; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; var sub = a.toBQL(); if ( OrExpr.isInstance(a) ) { sub = '(' + sub + ')'; } s += sub; if ( i < this.args.length-1 ) s += (' '); } return s; }, collectInputs: function(terms) { for ( var i = 0; i < this.args.length; i++ ) { this.args[i].collectInputs(terms); } }, minterm: function(index, term) { var out = true; for ( var i = 0; i < this.args.length; i++ ) { out = this.args[i].minterm(index, term) && out; } return out; } }, constants: { PARTIAL_AND_RULES: [ [ 'EqExpr', 'EqExpr', function(e1, e2) { return e1.arg1.exclusive ? e1.arg2.f() == e2.arg2.f() ? e1 : FALSE : e1.arg2.f() == e2.arg2.f() ? e1 : null ; } ], [ 'InExpr', 'InExpr', function(e1, e2) { var i = e1.arg1.exclusive ? e1.arg2.intersection(e2.arg2) : e1.arg2.union(e2.arg2) ; return i.length ? IN(e1.arg1, i) : FALSE; } ], [ 'InExpr', 'ContainedInICExpr', function(e1, e2) { if ( ! e1.arg1.exclusive ) return null; var i = e1.arg2.filter(function(o) { o = o.toUpperCase(); return e2.arg2.some(function(o2) { return o.indexOf(o2) != -1; }); }); return i.length ? IN(e1.arg1, i) : FALSE; } ], [ 'ContainedInICExpr', 'ContainedInICExpr', function(e1, e2) { console.assert(false, 'AND.partialEval: ContainedInICExpr has no partialEval rule'); } ], [ 'InExpr', 'ContainsICExpr', function(e1, e2) { if ( ! e1.arg1.exclusive ) return; var i = e1.arg2.filter(function(o) { return o.indexOfIC(e2.arg2.f()) !== -1; }); } ], [ 'InExpr', 'ContainsExpr', function(e1, e2) { if ( ! e1.arg1.exclusive ) return; var i = e1.arg2.filter(function(o) { return o.indexOf(e2.arg2.f()) !== -1; }); return i.length ? IN(e1.arg1, i) : FALSE; } ], [ 'EqExpr', 'InExpr', function(e1, e2) { if ( ! e1.arg1.exclusive ) return; return e2.arg2.indexOf(e1.arg2.f()) === -1 ? FALSE : e1; } ] ], partialAnd: function(e1, e2) { if ( OrExpr.isInstance(e2) ) { var tmp = e1; e1 = e2; e2 = tmp; } if ( OrExpr.isInstance(e1) ) { var args = []; for ( var i = 0 ; i < e1.args.length ; i++ ) { args.push(AND(e2, e1.args[i])); } return OrExpr.create({args: args}).partialEval(); } if ( ! BINARY.isInstance(e1) ) return null; if ( ! BINARY.isInstance(e2) ) return null; if ( e1.arg1 != e2.arg1 ) return null; var RULES = this.PARTIAL_AND_RULES; for ( var i = 0 ; i < RULES.length ; i++ ) { if ( e1.model_.name == RULES[i][0] && e2.model_.name == RULES[i][1] ) return RULES[i][2](e1, e2); if ( e2.model_.name == RULES[i][0] && e1.model_.name == RULES[i][1] ) return RULES[i][2](e2, e1); } if ( DEBUG ) console.log('Unknown partialAnd combination: ', e1.name_, e2.name_); return null; }, partialEval: function() { var newArgs = []; var updated = false; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; var newA = this.args[i].partialEval(); if ( newA === FALSE ) return FALSE; if ( AndExpr.isInstance(newA) ) { // In-line nested AND clauses for ( var j = 0 ; j < newA.args.length ; j++ ) { newArgs.push(newA.args[j]); } updated = true; } else { if ( newA === TRUE ) { updated = true; } else { newArgs.push(newA); if ( a !== newA ) updated = true; } } } for ( var i = 0 ; i < newArgs.length-1 ; i++ ) { for ( var j = i+1 ; j < newArgs.length ; j++ ) { var a = this.partialAnd(newArgs[i], newArgs[j]); if ( a ) { console.log('***************** ', newArgs[i].toMQL(), ' <PartialAnd> ', newArgs[j].toMQL(), ' -> ', a.toMQL()); if ( a === FALSE ) return FALSE; newArgs[i] = a; newArgs.splice(j, 1); } } } if ( newArgs.length == 0 ) return TRUE; if ( newArgs.length == 1 ) return newArgs[0]; return updated ? AndExpr.create({args: newArgs}) : this; }, f: function(obj) { return this.args.every(function(arg) { return arg.f(obj); }); } } }); function AND() { return AndExpr.create({args: compileArray_.call(null, arguments)}); } CLASS({ name: 'NeqExpr', extendsModel: 'BINARY', abstract: true, methods: { toSQL: function() { return this.arg1.toSQL() + '<>' + this.arg2.toSQL(); }, toMQL: function() { return '-' + this.arg1.toMQL() + '=' + this.arg2.toMQL(); }, toBQL: function() { return '-' + this.arg1.toBQL() + ':' + this.arg2.toBQL(); }, partialEval: function() { var newArg1 = this.arg1.partialEval(); var newArg2 = this.arg2.partialEval(); if ( ConstantExpr.isInstance(newArg1) && ConstantExpr.isInstance(newArg2) ) { return compile_(newArg1.f() != newArg2.f()); } return this.arg1 !== newArg1 || this.arg2 != newArg2 ? NeqExpr.create({arg1: newArg1, arg2: newArg2}) : this; }, f: function(obj) { return this.arg1.f(obj) != this.arg2.f(obj); } } }); function NEQ(arg1, arg2) { return NeqExpr.create({arg1: compile_(arg1), arg2: compile_(arg2)}); } CLASS({ name: 'UpperExpr', extendsModel: 'UNARY', properties: [ { name: 'label_', defaultValue: 'UPPER' } ], methods: [ function partialEval() { var newArg1 = this.arg1.partialEval(); if ( ConstantExpr.isInstance(newArg1) ) { var val = newArg1.f(); if ( typeof val === 'string' ) return compile_(val); } else if ( Array.isArray(newArg1) ) { debugger; } return this; }, function f(obj) { var a = this.arg1.f(obj); return a && a.toUpperCase ? a.toUpperCase() : a ; } ] }); function UPPER(arg1) { return UpperExpr.create({arg1: compile_(arg1)}); } function EQ_IC(arg1, arg2) { return EQ(UPPER(arg1), UPPER(arg2)); } function IN_IC(arg1, arg2) { return IN(UPPER(arg1), UPPER(arg2)); } /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ CLASS({ name: 'MaxExpr', extendsModel: 'UNARY', properties: [ { name: 'max', type: 'int', help: 'Maximum value.', defaultValue: undefined } ], methods: { maximum: function(o1, o2) { return o1.compareTo(o2) > 0 ? o1 : o2; }, reduce: function(other) { return MaxExpr.create({max: this.maximum(this.max, other.max)}); }, reduceI: function(other) { this.max = this.maximum(this.max, other.max); }, pipe: function(sink) { sink.put(this); }, put: function(obj) { var v = this.arg1.f(obj); this.max = this.max === undefined ? v : this.maximum(this.max, v); }, remove: function(obj) { }, toString: function() { return this.max; } } }); function MAX(expr) { return MaxExpr.create({arg1: expr}); } CLASS({ name: 'InExpr', extendsModel: 'BINARY', documentation: 'Binary expression which is true if its first argument is EQ to any element of its second argument, which is an array.', properties: [ { name: 'arg2', label: 'Argument', type: 'Expr', help: 'Sub-expression', postSet: function() { this.valueSet_ = undefined; } } ], methods: { partialEval: function() { if ( this.arg2.length == 1 ) return EQ(this.arg1, this.arg2[0]); return this; }, valueSet: function() { if ( ! this.valueSet_ ) { var s = {}; for ( var i = 0 ; i < this.arg2.length ; i++ ) s[this.arg2[i]] = true; this.valueSet_ = s; } return this.valueSet_; }, toSQL: function() { return this.arg1.toSQL() + ' IN ' + this.arg2; }, toMQL: function() { return this.arg1.toMQL() + '=' + this.arg2.join(',') }, toBQL: function() { return this.arg1.toBQL() + ':(' + this.arg2.join('|') + ')' }, f: function(obj) { return this.valueSet().hasOwnProperty(this.arg1.f(obj)); } } }); function IN(arg1, arg2) { return InExpr.create({arg1: compile_(arg1), arg2: arg2 }); } CLASS({ name: 'LtExpr', extendsModel: 'BINARY', abstract: true, methods: { toSQL: function() { return this.arg1.toSQL() + '<' + this.arg2.toSQL(); }, toMQL: function() { return this.arg1.toMQL() + '-before:' + this.arg2.toMQL(); }, toBQL: function() { return this.arg1.toBQL() + '<' + this.arg2.toBQL(); }, partialEval: function() { var newArg1 = this.arg1.partialEval(); var newArg2 = this.arg2.partialEval(); if ( ConstantExpr.isInstance(newArg1) && ConstantExpr.isInstance(newArg2) ) { return compile_(newArg1.f() < newArg2.f()); } return this.arg1 !== newArg1 || this.arg2 != newArg2 ? LtExpr.create({arg1: newArg1, arg2: newArg2}) : this; }, f: function(obj) { return this.arg1.f(obj) < this.arg2.f(obj); } } }); function LT(arg1, arg2) { return LtExpr.create({arg1: compile_(arg1), arg2: compile_(arg2)}); } CLASS({ name: 'GtExpr', extendsModel: 'BINARY', abstract: true, methods: { toSQL: function() { return this.arg1.toSQL() + '>' + this.arg2.toSQL(); }, toMQL: function() { return this.arg1.toMQL() + '-after:' + this.arg2.toMQL(); }, toBQL: function() { return this.arg1.toBQL() + '>' + this.arg2.toBQL(); }, partialEval: function() { var newArg1 = this.arg1.partialEval(); var newArg2 = this.arg2.partialEval(); if ( ConstantExpr.isInstance(newArg1) && ConstantExpr.isInstance(newArg2) ) { return compile_(newArg1.f() > newArg2.f()); } return this.arg1 !== newArg1 || this.arg2 != newArg2 ? GtExpr.create({arg1: newArg1, arg2: newArg2}) : this; }, f: function(obj) { return this.arg1.f(obj) > this.arg2.f(obj); } } }); function GT(arg1, arg2) { return GtExpr.create({arg1: compile_(arg1), arg2: compile_(arg2)}); } CLASS({ name: 'LteExpr', extendsModel: 'BINARY', abstract: true, methods: { toSQL: function() { return this.arg1.toSQL() + '<=' + this.arg2.toSQL(); }, toMQL: function() { return this.arg1.toMQL() + '-before:' + this.arg2.toMQL(); }, toBQL: function() { return this.arg1.toBQL() + '<=' + this.arg2.toBQL(); }, partialEval: function() { var newArg1 = this.arg1.partialEval(); var newArg2 = this.arg2.partialEval(); if ( ConstantExpr.isInstance(newArg1) && ConstantExpr.isInstance(newArg2) ) { return compile_(newArg1.f() <= newArg2.f()); } return this.arg1 !== newArg1 || this.arg2 != newArg2 ? LtExpr.create({arg1: newArg1, arg2: newArg2}) : this; }, f: function(obj) { return this.arg1.f(obj) <= this.arg2.f(obj); } } }); function LTE(arg1, arg2) { return LteExpr.create({arg1: compile_(arg1), arg2: compile_(arg2)}); } CLASS({ name: 'GteExpr', extendsModel: 'BINARY', abstract: true, methods: { toSQL: function() { return this.arg1.toSQL() + '>=' + this.arg2.toSQL(); }, toMQL: function() { return this.arg1.toMQL() + '-after:' + this.arg2.toMQL(); }, toBQL: function() { return this.arg1.toBQL() + '>=' + this.arg2.toBQL(); }, partialEval: function() { var newArg1 = this.arg1.partialEval(); var newArg2 = this.arg2.partialEval(); if ( ConstantExpr.isInstance(newArg1) && ConstantExpr.isInstance(newArg2) ) { return compile_(newArg1.f() >= newArg2.f()); } return this.arg1 !== newArg1 || this.arg2 != newArg2 ? GtExpr.create({arg1: newArg1, arg2: newArg2}) : this; }, f: function(obj) { return this.arg1.f(obj) >= this.arg2.f(obj); } } }); function GTE(arg1, arg2) { return GteExpr.create({arg1: compile_(arg1), arg2: compile_(arg2)}); } /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ CLASS({ name: 'ExplainExpr', extendsModel: 'UNARY', documentation: 'Pseudo-expression which outputs a human-readable description of its subexpression, and the plan for evaluating it.', properties: [ { name: 'plan', help: 'Execution Plan', defaultValue: "" } ], methods: { toString: function() { return this.plan; }, toSQL: function() { return this.arg1.toSQL(); }, toMQL: function() { return this.arg1.toMQL(); }, toBQL: function() { return this.arg1.toBQL(); }, partialEval: function() { var newArg = this.arg1.partialEval(); return this.arg1 === newArg ? this : EXPLAIN(newArg); }, f: function(obj) { return this.arg1.f(obj); } } }); function EXPLAIN(arg) { return ExplainExpr.create({arg1: arg}); } CLASS({ name: 'OrExpr', extendsModel: 'NARY', documentation: 'N-ary expression which is true if any one of its 0 or more subexpressions is true. OR() === FALSE', methods: { toSQL: function() { var s; s = '('; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; s += a.toSQL(); if ( i < this.args.length-1 ) s += (' OR '); } s += ')'; return s; }, toMQL: function() { var s = ''; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; s += a.toMQL(); if ( i < this.args.length-1 ) s += (' OR '); } return s; }, toBQL: function() { var s = ''; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; s += a.toBQL(); if ( i < this.args.length-1 ) s += (' | '); } return s; }, collectInputs: function(terms) { for ( var i = 0; i < this.args.length; i++ ) { this.args[i].collectInputs(terms); } }, minterm: function(index, term) { var out = false; for ( var i = 0; i < this.args.length; i++ ) { out = this.args[i].minterm(index, term) || out; } return out; } }, constants: { PARTIAL_OR_RULES: [ [ 'InExpr', 'EqExpr', function(e1, e2) { return IN(e1.arg1, e1.arg1.union([e2.arg2.f()])); } ], [ 'InExpr', 'InExpr', function(e1, e2) { var i = e1.arg2.filter(function(o) { return e2.arg2.indexOf(o) !== -1; }); return IN(e1.arg1, e1.arg2.union(e2.arg2)); } ] /* [ 'InExpr', 'ContainsICExpr', function(e1, e2) { var i = e1.arg2.filter(function(o) { return o.indexOfIC(e2.arg2.f()) !== -1; }); return i.length ? IN(e1.arg1, i) : FALSE; } ], [ 'InExpr', 'ContainsExpr', function(e1, e2) { var i = e1.arg2.filter(function(o) { return o.indexOf(e2.arg2.f()) !== -1; }); return i.length ? IN(e1.arg1, i) : FALSE; } ], [ 'EqExpr', 'InExpr', function(e1, e2) { return e2.arg2.indexOf(e1.arg2.f()) === -1 ? FALSE : e1; } ]*/ ], partialOr: function(e1, e2) { if ( ! BINARY.isInstance(e1) ) return null; if ( ! BINARY.isInstance(e2) ) return null; if ( e1.arg1 != e2.arg1 ) return null; var RULES = this.PARTIAL_OR_RULES; for ( var i = 0 ; i < RULES.length ; i++ ) { if ( e1.model_.name == RULES[i][0] && e2.model_.name == RULES[i][1] ) return RULES[i][2](e1, e2); if ( e2.model_.name == RULES[i][0] && e1.model_.name == RULES[i][1] ) return RULES[i][2](e2, e1); } console.log('************** Unknown partialOr combination: ', e1.name_, e2.name_); return null; }, partialEval: function() { var newArgs = []; var updated = false; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; var newA = this.args[i].partialEval(); if ( newA === TRUE ) return TRUE; if ( OrExpr.isInstance(newA) ) { // In-line nested OR clauses for ( var j = 0 ; j < newA.args.length ; j++ ) { newArgs.push(newA.args[j]); } updated = true; } else { if ( newA !== FALSE ) { newArgs.push(newA); } if ( a !== newA ) updated = true; } } for ( var i = 0 ; i < newArgs.length-1 ; i++ ) { for ( var j = i+1 ; j < newArgs.length ; j++ ) { var a = this.partialOr(newArgs[i], newArgs[j]); if ( a ) { console.log('***************** ', newArgs[i].toMQL(), ' <PartialOr> ', newArgs[j].toMQL(), ' -> ', a.toMQL()); if ( a === TRUE ) return TRUE; newArgs[i] = a; newArgs.splice(j, 1); } } } if ( newArgs.length == 0 ) return FALSE; if ( newArgs.length == 1 ) return newArgs[0]; return updated ? OrExpr.create({args: newArgs}) : this; }, f: function(obj) { return this.args.some(function(arg) { return arg.f(obj); }); } } }); CLASS({ name: 'NotExpr', extendsModel: 'UNARY', abstract: true, documentation: 'Unary expression which inverts the truth value of its argument.', methods: { toSQL: function() { return 'not ( ' + this.arg1.toSQL() + ' )'; }, toMQL: function() { // TODO: only include params if necessary return '-' + this.arg1.toMQL(); }, toBQL: function() { // TODO: only include params if necessary return '-' + this.arg1.toBQL(); }, collectInputs: function(terms) { this.arg1.collectInputs(terms); }, minterm: function(index, term) { return ! this.arg1.minterm(index, term); }, partialEval: function() { var newArg = this.arg1.partialEval(); if ( newArg === TRUE ) return FALSE; if ( newArg === FALSE ) return TRUE; if ( NotExpr.isInstance(newArg) ) return newArg.arg1; if ( EqExpr.isInstance(newArg) ) return NeqExpr.create(newArg); if ( NeqExpr.isInstance(newArg) ) return EqExpr.create(newArg); if ( LtExpr.isInstance(newArg) ) return GteExpr.create(newArg); if ( GtExpr.isInstance(newArg) ) return LteExpr.create(newArg); if ( LteExpr.isInstance(newArg) ) return GtExpr.create(newArg); if ( GteExpr.isInstance(newArg) ) return LtExpr.create(newArg); return this.arg1 === newArg ? this : NOT(newArg); }, f: function(obj) { return ! this.arg1.f(obj); } } }); CLASS({ name: 'ContainedInICExpr', extendsModel: 'BINARY', documentation: 'Checks if the first argument is contained in the array-valued right argument, ignoring case in strings.', properties: [ { name: 'arg2', label: 'Argument', type: 'Expr', help: 'Sub-expression', preSet: function(_, a) { return a.map(function(o) { return o.toUpperCase(); }); } } ], methods: { toSQL: function() { return this.arg1.toSQL() + ' IN ' + this.arg2; }, toMQL: function() { return this.arg1.toMQL() + ':' + this.arg2.join(',') }, toBQL: function() { return this.arg1.toBQL() + ':(' + this.arg2.join('|') + ')' }, f: function(obj) { var v = this.arg1.f(obj); if ( Array.isArray(v) ) { for ( var j = 0 ; j < v.length ; j++ ) { var a = v[j].toUpperCase(); for ( var i = 0 ; i < this.arg2.length ; i++ ) { if ( a.indexOf(this.arg2[i]) != -1 ) return true; } } } else { v = ('' + v).toUpperCase(); for ( var i = 0 ; i < this.arg2.length ; i++ ) { if ( v.indexOf(this.arg2[i]) != -1 ) return true; } } return false; } } }); CLASS({ name: 'ContainsExpr', extendsModel: 'BINARY', //documentation: 'Checks methods: { toSQL: function() { return this.arg1.toSQL() + " like '%' + " + this.arg2.toSQL() + "+ '%'"; }, toMQL: function() { return this.arg1.toMQL() + ':' + this.arg2.toMQL(); }, toBQL: function() { return this.arg1.toBQL() + ':' + this.arg2.toBQL(); }, partialEval: function() { var newArg1 = this.arg1.partialEval(); var newArg2 = this.arg2.partialEval(); if ( ConstantExpr.isInstance(newArg1) && ConstantExpr.isInstance(newArg2) ) { return compile_(newArg1.f().indexOf(newArg2.f()) != -1); } return this.arg1 !== newArg1 || this.arg2 != newArg2 ? ContainsExpr.create({arg1: newArg1, arg2: newArg2}) : this; }, f: function(obj) { var arg1 = this.arg1.f(obj); var arg2 = this.arg2.f(obj); if ( Array.isArray(arg1) ) { return arg1.some(function(arg) { return arg.indexOf(arg2) != -1; }); } return arg1.indexOf(arg2) != -1; } } }); CLASS({ name: 'ContainsICExpr', extendsModel: 'BINARY', properties: [ { name: 'arg2', label: 'Argument', type: 'Expr', help: 'Sub-expression', defaultValue: TRUE, postSet: function(_, value) { this.pattern_ = undefined; } } ], methods: { // No different that the non IC-case toSQL: function() { return this.arg1.toSQL() + " like '%' + " + this.arg2.toSQL() + "+ '%'"; }, toMQL: function() { return this.arg1.toMQL() + ':' + this.arg2.toMQL(); }, toBQL: function() { return this.arg1.toBQL() + ':' + this.arg2.toBQL(); }, partialEval: function() { var newArg1 = this.arg1.partialEval(); var newArg2 = this.arg2.partialEval(); if ( ConstantExpr.isInstance(newArg1) && ConstantExpr.isInstance(newArg2) ) { return compile_(newArg1.f().toLowerCase().indexOf(newArg2.f()) != -1); } return this.arg1 !== newArg1 || this.arg2 != newArg2 ? ContainsICExpr.create({arg1: newArg1, arg2: newArg2}) : this; }, f: function(obj) { var arg1 = this.arg1.f(obj); // Escape Regex escape characters var pattern = this.pattern_ || ( this.pattern_ = new RegExp(this.arg2.f().toString().replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'i') ); if ( Array.isArray(arg1) ) { var pattern = this.pattern_; return arg1.some(function(arg) { return pattern.test(arg); }); } return this.pattern_.test(arg1); } } }); // TODO: A TrieIndex would be ideal for making this very fast. CLASS({ name: 'StartsWithExpr', extendsModel: 'BINARY', methods: { toSQL: function() { return this.arg1.toSQL() + " like '%' + " + this.arg2.toSQL() + "+ '%'"; }, // TODO: Does MQL support this operation? toMQL: function() { return this.arg1.toMQL() + '-after:' + this.arg2.toMQL(); }, // TODO: Likewise BQL. toBQL: function() { return this.arg1.toBQL() + '>=' + this.arg2.toBQL(); }, partialEval: function() { var newArg1 = this.arg1.partialEval(); var newArg2 = this.arg2.partialEval(); if ( ConstantExpr.isInstance(newArg1) && ConstantExpr.isInstance(newArg2) ) { return compile_(newArg1.f().startsWith(newArg2.f())); } return this.arg1 !== newArg1 || this.arg2 != newArg2 ? StartsWithExpr.create({arg1: newArg1, arg2: newArg2}) : this; }, f: function(obj) { var arg1 = this.arg1.f(obj); var arg2 = this.arg2.f(obj); if ( Array.isArray(arg1) ) { return arg1.some(function(arg) { return arg.startsWith(arg2); }); } return arg1.startsWith(arg2); } } }); CLASS({ name: 'StartsWithICExpr', extendsModel: 'BINARY', methods: { toSQL: function() { return this.arg1.toSQL() + " like '%' + " + this.arg2.toSQL() + "+ '%'"; }, // TODO: Does MQL support this operation? toMQL: function() { return this.arg1.toMQL() + '-after:' + this.arg2.toMQL(); }, // TODO: Does BQL support this operation? toBQL: function() { return this.arg1.toBQL() + '>=' + this.arg2.toBQL(); }, partialEval: function() { var newArg1 = this.arg1.partialEval(); var newArg2 = this.arg2.partialEval(); if ( ConstantExpr.isInstance(newArg1) && ConstantExpr.isInstance(newArg2) ) { return compile_(newArg1.f().startsWithIC(newArg2.f())); } return this.arg1 !== newArg1 || this.arg2 != newArg2 ? StartsWithICExpr.create({arg1: newArg1, arg2: newArg2}) : this; }, f: function(obj) { return this.arg1.f(obj).startsWithIC(this.arg2.f(obj)); } } }); CLASS({ name: 'ConcatExpr', extendsModel: 'NARY', label: 'concat', methods: { partialEval: function() { // TODO: implement return this; }, f: function(obj) { var str = []; for ( var i = 0 ; i < this.args.length ; i++ ) { str.push(this.args[i].f(obj)); } return str.join(''); } } }); CLASS({ name: 'SumExpr', extendsModel: 'UNARY', properties: [ { name: 'sum', type: 'int', help: 'Sum of values.', factory: function() { return 0; } } ], methods: { pipe: function(sink) { sink.put(this); }, put: function(obj) { this.instance_.sum += this.arg1.f(obj); }, remove: function(obj) { this.sum -= this.arg1.f(obj); }, toString: function() { return this.sum; } } }); CLASS({ name: 'AvgExpr', extendsModel: 'UNARY', properties: [ { name: 'count', type: 'int', defaultValue: 0 }, { name: 'sum', type: 'int', help: 'Sum of values.', defaultValue: 0 }, { name: 'avg', type: 'floag', help: 'Average of values.', getter: function() { return this.sum / this.count; } } ], methods: { pipe: function(sink) { sink.put(this); }, put: function(obj) { this.count++; this.sum += this.arg1.f(obj); }, remove: function(obj) { this.count--; this.sum -= this.arg1.f(obj); }, toString: function() { return this.avg; } } }); CLASS({ name: 'MinExpr', extendsModel: 'UNARY', properties: [ { name: 'min', type: 'int', help: 'Minimum value.', defaultValue: undefined } ], methods: { minimum: function(o1, o2) { return o1.compareTo(o2) > 0 ? o2 : o1; }, reduce: function(other) { return MinExpr.create({max: this.mininum(this.min, other.min)}); }, reduceI: function(other) { this.min = this.minimum(this.min, other.min); }, pipe: function(sink) { sink.put(this); }, put: function(obj) { var v = this.arg1.f(obj); this.min = this.min === undefined ? v : this.minimum(this.min, v); }, remove: function(obj) { }, toString: function() { return this.min; } } }); CLASS({ name: 'DistinctExpr', extendsModel: 'BINARY', properties: [ { name: 'values', help: 'Distinct values.', factory: function() { return {}; } } ], methods: { reduce: function(other) { // TODO: }, reduceI: function(other) { // TODO: }, put: function(obj) { var key = this.arg1.f(obj); if ( this.values.hasOwnProperty(key) ) return; this.values[key] = true; this.arg2.put(obj); }, remove: function(obj) { /* TODO: */ }, toString: function() { return this.arg2.toString(); }, toHTML: function() { return this.arg2.toHTML(); } } }); CLASS({ name: 'GroupByExpr', extendsModel: 'BINARY', properties: [ { name: 'groups', type: 'Map[Expr]', help: 'Groups.', factory: function() { return {}; } }, { // Maintain a mapping of real keys because the keys in // 'groups' are actually the toString()'s of the real keys // and his interferes with the property comparator used to // sort groups. name: 'groupKeys', factory: function() { return [] } } ], methods: { sortedGroups: function(opt_comparator) { var c = opt_comparator || this.arg1.compareProperty; this.groupKeys.sort(c); var ret = {}; for ( var i = 0 ; i < this.groupKeys.length ; i++ ) { ret[this.groupKeys[i]] = this.groups[i]; } return ret; }, reduce: function(other) { // TODO: }, reduceI: function(other) { for ( var i in other.groups ) { if ( this.groups[i] ) this.groups[i].reduceI(other.groups[i]); else this.groups[i] = other.groups[i].deepClone(); } }, pipe: function(sink) { for ( key in this.groups ) { sink.push([key, this.groups[key].toString()]); } return sink; }, putInGroup_: function(key, obj) { var group = this.groups.hasOwnProperty(key) && this.groups[key]; if ( ! group ) { group = this.arg2.clone(); this.groups[key] = group; this.groupKeys.push(key); } group.put(obj); }, put: function(obj) { var key = this.arg1.f(obj); if ( Array.isArray(key) ) { if ( key.length ) { for ( var i = 0 ; i < key.length ; i++ ) this.putInGroup_(key[i], obj); } else { // Perhaps we should use a key value of undefiend instead of '', since // '' may actually be a valid key. this.putInGroup_('', obj); } } else { this.putInGroup_(key, obj); } }, clone: function() { // Don't use default clone because we don't want to copy 'groups' return GroupByExpr.create({arg1: this.arg1, arg2: this.arg2}); }, remove: function(obj) { /* TODO: */ }, toString: function() { return this.groups; }, deepClone: function() { var cl = this.clone(); cl.groups = {}; for ( var i in this.groups ) { cl.groups[i] = this.groups[i].deepClone(); } return cl; }, toView_: function() { return this; }, toHTML: function() { var out = []; out.push('<table border=1>'); for ( var key in this.groups ) { var value = this.groups[key]; var str = value.toView_ ? value.toView_().toHTML() : value; out.push('<tr><th>', key, '</th><td>', str, '</td></tr>'); } out.push('</table>'); return out.join(''); }, initHTML: function() { for ( var key in this.groups ) { var value = this.groups[key]; value.toView_ && value.toView_().initHTML(); } } } }); CLASS({ name: 'GridByExpr', extendsModel: 'Expr', properties: [ { name: 'xFunc', label: 'X-Axis Function', type: 'Expr', help: 'Sub-expression', defaultValue: TRUE }, { name: 'yFunc', label: 'Y-Axis Function', type: 'Expr', help: 'Sub-expression', defaultValue: TRUE }, { name: 'acc', label: 'Accumulator', type: 'Expr', help: 'Sub-expression', defaultValue: TRUE }, { name: 'rows', type: 'Map[Expr]', help: 'Rows.', factory: function() { return {}; } }, { name: 'cols', label: 'Columns', type: 'Map[Expr]', help: 'Columns.', factory: function() { return {}; } }, { model_: 'ArrayProperty', name: 'children' } ], methods: { init: function() { this.SUPER(); var self = this; var f = function() { self.cols = GROUP_BY(self.xFunc, COUNT()); self.rows = GROUP_BY(self.yFunc, GROUP_BY(self.xFunc, self.acc)); }; self.addPropertyListener('xFunc', f); self.addPropertyListener('yFunc', f); self.addPropertyListener('acc', f); f(); /* Events.dynamic( function() { self.xFunc; self.yFunc; self.acc; }, function() { self.cols = GROUP_BY(self.xFunc, COUNT()); self.rows = GROUP_BY(self.yFunc, GROUP_BY(self.xFunc, self.acc)); }); */ }, reduce: function(other) { }, reduceI: function(other) { }, pipe: function(sink) { }, put: function(obj) { this.rows.put(obj); this.cols.put(obj); }, clone: function() { // Don't use default clone because we don't want to copy 'groups' return this.model_.create({xFunc: this.xFunc, yFunc: this.yFunc, acc: this.acc}); }, remove: function(obj) { /* TODO: */ }, toString: function() { return this.groups; }, deepClone: function() { }, renderCell: function(x, y, value) { var str = value ? (value.toHTML ? value.toHTML() : value) : ''; if ( value && value.toHTML && value.initHTML ) this.children.push(value); return '<td>' + str + '</td>'; }, sortAxis: function(values, f) { return values.sort(f.compareProperty); }, sortCols: function(cols, xFunc) { return this.sortAxis(cols, xFunc); }, sortRows: function(rows, yFunc) { return this.sortAxis(rows, yFunc); }, sortedCols: function() { return this.sortCols( this.cols.groupKeys, this.xFunc); }, sortedRows: function() { return this.sortRows( this.rows.groupKeys, this.yFunc); }, toHTML_: function() { return this; }, toHTML: function() { var out; this.children = []; var cols = this.cols.groups; var rows = this.rows.groups; var sortedCols = this.sortedCols(); var sortedRows = this.sortedRows(); out = '<table border=0 cellspacing=0 class="gridBy"><tr><th></th>'; for ( var i = 0 ; i < sortedCols.length ; i++ ) { var x = sortedCols[i]; var str = x.toHTML ? x.toHTML() : x; out += '<th>' + str + '</th>'; } out += '</tr>'; for ( var j = 0 ; j < sortedRows.length ; j++ ) { var y = sortedRows[j]; out += '<tr><th>' + y + '</th>'; for ( var i = 0 ; i < sortedCols.length ; i++ ) { var x = sortedCols[i]; var value = rows[y].groups[x]; if ( value ) { value.x = x; value.y = y; } out += this.renderCell(x, y, value); } out += '</tr>'; } out += '</table>'; return out; }, initHTML: function() { for ( var i = 0; i < this.children.length; i++ ) { this.children[i].initHTML(); } this.children = []; } } }); CLASS({ name: 'MapExpr', extendsModel: 'BINARY', methods: { reduce: function(other) { // TODO: }, reduceI: function(other) { }, pipe: function(sink) { }, put: function(obj) { var val = this.arg1.f ? this.arg1.f(obj) : this.arg1(obj); var acc = this.arg2; acc.put(val); }, clone: function() { // Don't use default clone because we don't want to copy 'groups' return MapExpr.create({arg1: this.arg1, arg2: this.arg2.clone()}); }, remove: function(obj) { /* TODO: */ }, toString: function() { return this.arg2.toString(); }, deepClone: function() { }, toHTML: function() { return this.arg2.toHTML ? this.arg2.toHTML() : this.toString(); }, initHTML: function() { this.arg2.initHTML && this.arg2.initHTML(); } } }); CLASS({ name: 'SeqExpr', extendsModel: 'NARY', methods: { pipe: function(sink) { sink.put(this); }, put: function(obj) { var ret = []; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; a.put(obj); } }, f: function(obj) { var ret = []; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; ret.push(a.f(obj)); } return ret; }, clone: function() { return SeqExpr.create({args:this.args.clone()}); }, toString: function(obj) { var out = []; out.push('('); for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; out.push(a.toString()); if ( i < this.args.length-1 ) out.push(','); } out.push(')'); return out.join(''); }, toHTML: function(obj) { var out = []; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; out.push(a.toHTML ? a.toHTML() : a.toString()); if ( i < this.args.length-1 ) out.push('&nbsp;'); } return out.join(''); } } }); CLASS({ name: 'UpdateExpr', extendsModel: 'NARY', label: 'UpdateExpr', properties: [ { name: 'dao', type: 'DAO', transient: true, hidden: true } ], methods: { // TODO: put this back to process one at a time and then // have MDAO wait until it's done before pushing all data. put: function(obj) { (this.objs_ || (this.objs_ = [])).push(obj); }, eof: function() { if ( ! this.objs_ ) return; for ( var i = 0 ; i < this.objs_.length ; i++ ) { var obj = this.objs_[i]; var newObj = this.f(obj); if (newObj.id !== obj.id) this.dao.remove(obj.id); this.dao.put(newObj); } this.objs_ = undefined; }, f: function(obj) { var newObj = obj.clone(); for (var i = 0; i < this.args.length; i++) { this.args[i].f(newObj); } return newObj; }, reduce: function(other) { return UpdateExpr.create({ args: this.args.concat(other.args), dao: this.dao }); }, reduceI: function(other) { this.args = this.args.concat(other.args); }, toString: function() { return this.toSQL(); }, toSQL: function() { var s = 'SET '; for ( var i = 0 ; i < this.args.length ; i++ ) { var a = this.args[i]; s += a.toSQL(); if ( i < this.args.length-1 ) s += ', '; } return s; } } }); CLASS({ name: 'SetExpr', label: 'SetExpr', extendsModel: 'BINARY', methods: { toSQL: function() { return this.arg1.toSQL() + ' = ' + this.arg2.toSQL(); }, f: function(obj) { // TODO: This should be an assertion when arg1 is set rather than be checked // for every invocation. if ( Property.isInstance(this.arg1) ) { obj[this.arg1.name] = this.arg2.f(obj); } } } }); function SUM(expr) { return SumExpr.create({arg1: expr}); } function MIN(expr) { return MinExpr.create({arg1: expr}); } function AVG(expr) { return AvgExpr.create({arg1: expr}); } function SEQ() { // return SeqExpr.create({args: compileArray_.call(null, arguments)}); return SeqExpr.create({args: argsToArray(arguments)}); } function UPDATE(expr, dao) { return UpdateExpr.create({ args: compileArray_.call(null, Array.prototype.slice.call(arguments, 0, -1)), dao: arguments[arguments.length - 1] }); } function SET(arg1, arg2) { return SetExpr.create({ arg1: compile_(arg1), arg2: compile_(arg2) }); } function GROUP_BY(expr1, opt_expr2) { return GroupByExpr.create({arg1: expr1, arg2: opt_expr2 || [].sink}); } function GRID_BY(xFunc, yFunc, acc) { return GridByExpr.create({xFunc: xFunc, yFunc: yFunc, acc: acc}); } function MAP(fn, opt_sink) { return MapExpr.create({arg1: fn, arg2: opt_sink || [].sink}); } function DISTINCT(fn, sink) { return DistinctExpr.create({arg1: fn, arg2: sink}); } function OR() { return OrExpr.create({args: compileArray_.call(null, arguments)}); } function NOT(arg) { return NotExpr.create({arg1: compile_(arg)}); } // TODO: add EQ_ic function STARTS_WITH(arg1, arg2) { return StartsWithExpr.create({arg1: compile_(arg1), arg2: compile_(arg2)}); } function STARTS_WITH_IC(arg1, arg2) { return StartsWithICExpr.create({arg1: compile_(arg1), arg2: compile_(arg2)}); } function CONTAINS(arg1, arg2) { return ContainsExpr.create({arg1: compile_(arg1), arg2: compile_(arg2)}); } function CONTAINS_IC(arg1, arg2) { return ContainsICExpr.create({arg1: compile_(arg1), arg2: compile_(arg2)}); } function CONCAT() { return ConcatExpr.create({args: compileArray_.call(null, arguments)}); } CLASS({ name: 'TreeExpr', extendsModel: 'Expr', properties: [ { name: 'parentProperty' }, { name: 'childrenProperty' }, { name: 'items_', help: 'Temporary map to store collected objects.', factory: function() { return {}; }, transient: true }, { model_: 'ArrayProperty', name: 'roots' } ], methods: { put: function(o) { this.items_[o.id] = o; if ( ! this.parentProperty.f(o) ) { this.roots.push(o); } }, eof: function() { var pprop = this.parentProperty; var cprop = this.childrenProperty; for ( var key in this.items_ ) { var item = this.items_[key]; var parentId = pprop.f(item); if ( ! parentId ) continue; var parent = this.items_[parentId]; parent[cprop.name] = cprop.f(parent).concat(item); } // Remove temporary holder this.items_. this.items_ = {}; }, } }); function TREE(parentProperty, childrenProperty) { return TreeExpr.create({ parentProperty: parentProperty, childrenProperty: childrenProperty }); } CLASS({ name: 'DescExpr', extendsModel: 'UNARY', methods: { toSQL: function() { return this.arg1.toMQL() + 'DESC'; }, toMQL: function() { return '-' + this.arg1.toMQL(); }, compare: function(o1, o2) { return -1 * this.arg1.compare(o1, o2); } } }); CLASS({ name: 'AddExpr', extendsModel: 'BINARY', methods: { toSQL: function() { return this.arg1.toSQL() + ' + ' + this.arg2.toSQL(); }, f: function(o) { return this.arg1.f(o) + this.arg2.f(o); } } }); function ADD(arg1, arg2) { return AddExpr.create({ arg1: compile_(arg1), arg2: compile_(arg2) }); } function DESC(arg1) { if ( DescExpr.isInstance(arg1) ) return arg1.arg1; return DescExpr.create({ arg1: arg1 }); } var JOIN = function(dao, key, sink) { sink = sink || [].sink; return { f: function(o) { var s = sink.clone(); dao.where(EQ(key, o.id)).select(s); return [o, s]; } }; }; CLASS({ name: 'MQLExpr', extendsModel: 'UNARY', documentation: 'Parse an MQL query string and use it as a predicate.', properties: [ { name: 'specializations_', factory: function() { return {}; } } ], methods: { specialize: function(model) { var qp = QueryParserFactory(model, true /* keyword enabled */); return qp.parseString(this.arg1) || FALSE; }, specialization: function(model) { return this.specializations_[model.name] || ( this.specializations_[model.name] = this.specialize(model) ); }, // TODO: implement; toSQL: function() { return this.arg1; }, toMQL: function() { return this.arg1; }, partialEval: function() { return this; }, f: function(obj) { return this.specialization(obj.model_).f(obj); } } }); function MQL(mql) { return MQLExpr.create({arg1: mql}); } CLASS({ name: 'KeywordExpr', extendsModel: 'UNARY', documentation: 'Keyword search.', /* properties: [ { name: 'model', factory: function() { return {}; } } ], */ methods: { toSQL: function() { return this.arg1; }, toMQL: function() { return this.arg1; }, partialEval: function() { return this; }, f: function(obj) { // Escape Regex escape characters var pattern = this.pattern_ || ( this.pattern_ = new RegExp(this.arg1.toString().replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'i') ); return this.pattern_.test(obj.toJSON()); } } }); function KEYWORD(word) { return KeywordExpr.create({arg1: word}); } // TODO: add other Date functions var MONTH = function(p) { return {f: function (o) { return p.f(o).getMonth(); } }; }; /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ // TODO: move to package /** * Generic Google-like query-language parser generator. * * key:value key contains "value" * key=value key exactly matches "value" * key:value1,value2 key contains "value1" OR "value2" * key:(value1|value2) " * key1:value key2:value key1 contains value AND key2 contains "value" * key1:value AND key2:value " * key1:value and key2:value " * key1:value OR key2:value key1 contains value OR key2 contains "value" * key1:value or key2:value " * key:(-value) key does not contain "value" * (expr) groups expression * -expr not expression, ie. -pri:1 * NOT expr not expression, ie. NOT pri:1 * has:key key has a value * is:key key is a boolean TRUE value * key>value key is greater than value * key-after:value " * key<value key is less than value * key-before:value " * date:YY/MM/DD date specified * date:today date of today * date-after:today-7 date newer than 7 days ago * date:d1..d2 date within range d1 to d2, inclusive * key:me key is the current user * * Date formats: * YYYY * YYYY-MM * YYYY-MM-DD * YYYY-MM-DDTHH * YYYY-MM-DDTHH:MM */ var QueryParserFactory = function(model, opt_enableKeyword) { var g = { __proto__: grammar, START: sym('query'), query: sym('or'), or: repeat(sym('and'), alt(literal_ic(' OR '), literal(' | ')), 1), and: repeat( sym('expr'), alt(literal_ic('AND '), not(alt(literal_ic(' OR'), literal(' |')), ' ')), 1), expr: alt( sym('paren'), sym('negate'), sym('has'), sym('is'), sym('equals'), sym('before'), sym('after'), sym('id'), sym('keyword') ), paren: seq1(1, '(', sym('query'), ')'), negate: alt( seq('-', sym('expr')), seq('NOT ', sym('expr')) ), id: sym('number'), has: seq(literal_ic('has:'), sym('fieldname')), is: seq(literal_ic('is:'), sym('fieldname')), equals: seq(sym('fieldname'), alt(':', '='), sym('valueList')), // TODO: merge with 'equals' before: seq(sym('fieldname'), alt('<', '<=', '-before:'), sym('value')), // TODO: merge with 'equals' after: seq(sym('fieldname'), alt('>', '>=', '-after:'), sym('value')), value: alt( sym('me'), sym('date'), sym('string'), sym('number')), compoundValue: alt( sym('negateValue'), sym('orValue'), sym('andValue')), negateValue: seq('(', alt('-', literal_ic('not ')), sym('value'), ')'), orValue: seq( '(', repeat(sym('value'), alt('|', literal_ic(' or '), ' | '), 1), ')'), andValue: seq( '(', repeat(sym('value'), alt(literal_ic(' and '), ' '), 1), ')'), valueList: alt(sym('compoundValue'), repeat(sym('value'), ',', 1)), keyword: (function() { var keyword_ = sym('keyword_'); return function(ps) { return opt_enableKeyword && this.parse(keyword_, ps); } })(), keyword_: str(plus(notChar(' '))), me: seq(literal_ic('me'), lookahead(not(sym('char')))), date: alt( sym('range date'), sym('literal date'), sym('relative date')), 'range date': seq(sym('literal date'), '..', sym('literal date')), 'literal date': alt( // YYYY-MM-DDTHH:MM seq(sym('number'), '-', sym('number'), '-', sym('number'), 'T', sym('number'), ':', sym('number')), // YYYY-MM-DDTHH seq(sym('number'), '-', sym('number'), '-', sym('number'), 'T', sym('number')), // YYYY-MM-DD seq(sym('number'), '-', sym('number'), '-', sym('number')), // YYYY-MM seq(sym('number'), '-', sym('number')), // YY/MM/DD seq(sym('number'), '/', sym('number'), '/', sym('number'))), 'relative date': seq(literal_ic('today'), optional(seq('-', sym('number')))), string: alt( sym('word'), sym('quoted string')), 'quoted string': str(seq1(1, '"', repeat(alt(literal('\\"', '"'), notChar('"'))), '"')), word: str(plus(sym('char'))), char: alt(range('a','z'), range('A', 'Z'), range('0', '9'), '-', '^', '_', '@', '%', '.'), number: str(plus(range('0', '9'))) }; var fields = []; var properties = model.getRuntimeProperties() for ( var i = 0 ; i < properties.length ; i++ ) { var prop = properties[i]; fields.push(literal_ic(prop.name, prop)); for ( var j = 0 ; j < prop.aliases.length ; j++ ) if ( prop.aliases[j] ) fields.push(literal_ic(prop.aliases[j], prop)); if ( prop.shortName ) fields.push(literal_ic(prop.shortName, prop)); } fields.sort(function(a, b) { var d = a.length - b.length; if ( d !== 0 ) return d; if ( a == b ) return 0; return a < b ? 1 : -1; }); g.fieldname = alt.apply(null, fields); g.addActions({ id: function(v) { return EQ(model.ID, v); }, or: function(v) { return OR.apply(OR, v); }, and: function(v) { return AND.apply(AND, v); }, negate: function(v) { return NOT(v[1]); }, number: function(v) { return parseInt(v); }, me: function() { return this.ME || this.X.ME || ""; }, has: function(v) { return NEQ(v[1], ''); }, is: function(v) { return EQ(v[1], TRUE); }, before: function(v) { // If the value (v[2]) is a Date range, we take the appropriate end. if ( Array.isArray(v[2]) && v[2][0] instanceof Date ) { v[2] = v[1] === '<=' ? v[2][1] : v[2][0]; } return (v[1] === '<=' ? LTE : LT) (v[0], v[2]); }, after: function(v) { // If the value (v[2]) is a Date range, we take the appropriate end. if ( Array.isArray(v[2]) && v[2][0] instanceof Date ) { v[2] = v[1] === '>=' ? v[2][0] : v[2][1]; } return (v[1] === '>=' ? GTE : GT) (v[0], v[2]); }, equals: function(v) { // v[2], the values, is an array, which might have an 'and', 'or', or // 'negated' property on it. The default is 'or'. The partial evaluator // will simplify if these are needlessly complex. var prop = v[0]; var values = v[2]; var isInt = IntProperty.isInstance(prop); var isNum = isInt || FloatProperty.isInstance(prop); var isDateField = DateProperty.isInstance(prop) || DateTimeProperty.isInstance(prop); var isDateRange = Array.isArray(values[0]) && values[0][0] instanceof Date; if ( isDateField || isDateRange ) { if ( ! isDateRange ) { // Convert the number, a single year, into a date. Fortunately, years // are easy to add. var start = new Date(0); // Jan 1 1970 at midnight UTC. var end = new Date(0); start.setUTCFullYear(values[0]); end.setUTCFullYear(+values[0] + 1); values = [[start, end]]; } var q = AND(GTE(prop, values[0][0]), LT(prop, values[0][1])); return q; } var expr; if ( isNum ) { for ( var i = 0 ; i < values.length ; i++ ) values[i] = isInt ? parseInt(values[i]) : parseFloat(values[i]); expr = IN(v[0], values); } else { expr = ( v[1] === '=' ) ? IN_IC(v[0], values) : ContainedInICExpr.create({arg1: compile_(prop), arg2: values}) ; } if ( values.negated ) { return NOT(expr); } else if ( values.and ) { return AndExpr.create({ args: values.map(function(x) { return expr.model_.create({ arg1: expr.arg1, arg2: [x] }); }) }); } else { return expr; } }, keyword: function(v) { return KEYWORD(v); }, negateValue: function(v) { v.negated = true; return v; }, orValue: function(v) { v = v[1]; v.or = true; return v; }, andValue: function(v) { v = v[1]; v.and = true; return v; }, // All dates are actually treated as ranges. These are arrays of Date // objects: [start, end]. The start is inclusive and the end exclusive. // Using these objects, both ranges (date:2014, date:2014-05..2014-06) and // open-ended ranges (date>2014-01-01) can be computed higher up. // Date formats: // YYYY-MM-DDTHH:MM, YYYY-MM-DDTHH, YYYY-MM-DD, YYYY-MM, YY/MM/DD, YYYY 'literal date': function(v) { var start, end, interval; start = new Date(); end = new Date(); var ops = ['FullYear', 'Month', 'Date', 'Hours', 'Minutes', 'Seconds']; var defaults = [0, 1, 1, 0, 0, 0]; for (var i = 0; i < ops.length; i++) { var x = i*2 > v.length ? defaults[i] : v[i*2]; // Adjust for months being 0-based. start['setUTC' + ops[i]](x - (i == 1 ? 1 : 0)); end['setUTC' + ops[i]](x - (i == 1 ? 1 : 0)); } // Start and end are currently clones of each other. // Bump the last portion of the date and set it in end. var last = Math.floor(v.length / 2); var op = 'UTC' + ops[last]; end['set' + op](end['get' + op]() + 1); return [start, end]; }, 'relative date': function(v) { var d = new Date(); if ( v[1] ) d.setDate(d.getDate() - v[1][1]); return d; }, 'range date': function(v) { // This gives two dates, and we combined them, the range is from the start // of the first date to the end of the second. return [v[0][0], v[2][1]]; } }); return g; }; /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ var OAM = { time: function(name, fn) { return function() { console.time(name); var ret = fn.apply(this, arguments); console.timeEnd(name); return ret; }; }, profile: function(fn) { return function() { console.profile(); var ret = fn.apply(this, arguments); console.profileEnd(); return ret; }; } }; /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ var Visitor = { create: function() { return { __proto__: this, stack: [] }; }, push: function(o) { this.stack.push(o); }, pop: function() { return this.stack.pop(); }, top: function() { return this.stack.length && this.stack[this.stack.length-1]; }, visit: function(o) { return Array.isArray(o) ? this.visitArray(o) : ( typeof o === 'string' ) ? this.visitString(o) : ( typeof o === 'number' ) ? this.visitNumber(o) : ( o instanceof Function ) ? this.visitFunction(o) : ( o instanceof Date ) ? this.visitDate(o) : ( o === true ) ? this.visitTrue() : ( o === false ) ? this.visitFalse() : ( o === null ) ? this.visitNull() : ( o instanceof Object ) ? ( o.model_ ? this.visitObject(o) : this.visitMap(o) ) : this.visitUndefined() ; }, visitArray: function(o) { var len = o.length; for ( var i = 0 ; i < len ; i++ ) this.visitArrayElement(o, i); return o; }, visitArrayElement: function (arr, i) { this.visit(arr[i]); }, visitString: function(o) { return o; }, visitFunction: function(o) { return o; }, visitNumber: function(o) { return o; }, visitDate: function(o) { return o; }, visitObject: function(o) { var properties = o.model_.getRuntimeProperties(); for ( var key in properties ) { var prop = properties[key]; if ( prop.name in o.instance_ ) { this.visitProperty(o, prop); } } return o; }, visitProperty: function(o, prop) { this.visit(o[prop.name]); }, visitMap: function(o) { for ( var key in o ) { this.visitMapElement(key, o[key]); }; return o; }, visitMapElement: function(key, value) { }, visitTrue: function() { return true; }, visitFalse: function() { return false; }, visitNull: function() { return null; }, visitUndefined: function() { return undefined; } }; /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ CLASS({ name: 'XHR', properties: [ { model_: 'IntProperty', name: 'delay', defaultValue: 0 }, { model_: 'IntProperty', name: 'retries', defaultValue: 0 }, { name: 'authAgent' }, { name: 'responseType', defaultValue: 'text' } ], methods: { init: function(args) { this.SUPER(args); if ( this.delay ) this.addDecorator(DelayDecorator.create({ delayMs: this.delay })); if ( this.authAgent ) this.addDecorator(OAuthXhrDecorator.create({ authAgent: this.authAgent })); if ( this.retries ) this.addDecorator(RetryDecorator.create({ maxAttempts: this.retries })); }, makeXhr: function() { return new XMLHttpRequest(); }, open: function(xhr, method, url) { xhr.open(method, url); }, setRequestHeader: function(xhr, header, value) { xhr.setRequestHeader(header, value); }, configure: function(xhr) { xhr.responseType = this.responseType; this.setRequestHeader(xhr, "Content-Type", "application/json"); }, bindListeners: function(xhr, ret) { var self = this; xhr.onreadystatechange = function() { if ( xhr.readyState == 4 ) { if ( self.responseType === "json" && typeof xhr.response == "string" ) var response = JSON.parse(xhr.response); else response = xhr.response; ret(response, xhr); } } }, send: function(xhr, data) { xhr.send(data); }, asend: function(ret, url, data, method) { var xhr = this.makeXhr(); this.open(xhr, method || "GET", url); this.configure(xhr); this.bindListeners(xhr, ret); this.send(xhr, (data && data.toJSON) ? data.toJSON() : data); }, } }); CLASS({ name: "OAuthXhrDecorator", properties: [ 'authAgent' ], methods: { configure: function(decorator, delegate, args) { var xhr = args[0]; xhr.setRequestHeader("Authorization", "Bearer " + decorator.authAgent.accessToken); return delegate.apply(this, args); }, asend: function(decorator, delegate, args) { var ret = args[0]; args[0] = function(response, xhr) { if ( xhr.status === 401 ) { decorator.authAgent.refresh(function() { ret(response, xhr); }); } else { ret(response, xhr); } }; return delegate.apply(null, args); } } }); CLASS({ name: 'RetryDecorator', properties: [ { model_: 'IntProperty', name: 'maxAttempts', defaultValue: 3 } ], methods: { asend: function(decorator, delegate, args) { var originalRet = args[0]; var attempts = 0; var self = this; var response; awhile( function() { return true; }, aseq( function(ret) { args[0] = ret; delegate.apply(self, args); }, function(ret, response, xhr) { if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 404 || ++attempts >= decorator.maxAttempts ) { finished = true; originalRet(response, xhr); return; } ret(); }))(function(){}); } } }); CLASS({ name: 'DelayDecorator', properties: [ { model_: 'IntProperty', name: 'delayMs' }, ], methods: { decorateObject: function(target) { var asend = adelay(target.asend.bind(target), this.delayMs); target.decorate('asend', function(_, _, args) { asend.apply(null, args); }); } } }); CLASS({ name: 'XhrMessenger', properties: [ { model_: 'URLProperty', name: 'url' }, { model_: 'StringProperty', name: 'method', defaultValue: "POST" } ], methods: { put: function(obj, sink) { var xhr = this.Y.XHR.create(); xhr.asend(function(response, xhr) { if ( xhr.status >= 200 && xhr.status < 300 ) { sink && sink.put && sink.put(response); return; } sink && sink.error && sink.error([response, xhr]); }, this.url, obj, this.method); } } }); /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ // TODO: model and move out of core var LoggingDAO = { create: function(/*[logger], delegate*/) { var logger, delegate; if ( arguments.length == 2 ) { logger = arguments[0]; delegate = arguments[1]; } else { logger = console.log.bind(console); delegate = arguments[0]; } return { __proto__: delegate, put: function(obj, sink) { logger('put', obj); delegate.put(obj, sink); }, remove: function(query, sink) { logger('remove', query); delegate.remove(query, sink); }, select: function(sink, options) { logger('select', options || ""); return delegate.select(sink, options); }, removeAll: function(sink, options) { logger('removeAll', options); return delegate.removeAll(sink, options); } }; } }; // TODO: model and move out of core var TimingDAO = { create: function(name, delegate) { // Used to distinguish between concurrent operations var id; var activeOps = {put: 0, remove:0, find: 0, select: 0}; function start(op) { var str = name + '-' + op; var key = activeOps[op]++ ? str + '-' + (id++) : str; console.time(id); return [key, str, window.performance.now(), op]; } function end(act) { activeOps[act[3]]--; id--; console.timeEnd(act[0]); console.log('Timing: ', act[1], ' ', (window.performance.now()-act[2]).toFixed(3), ' ms'); } function endSink(act, sink) { return { put: function() { end(act); sink && sink.put && sink.put.apply(sink, arguments); }, remove: function() { end(act); sink && sink.remove && sink.remove.apply(sink, arguments); }, error: function() { end(act); sink && sink.error && sink.error.apply(sink, arguments); }, eof: function() { end(act); sink && sink.eof && sink.eof.apply(sink, arguments); } }; } return { __proto__: delegate, put: function(obj, sink) { var act = start('put'); delegate.put(obj, endSink(act, sink)); }, remove: function(query, sink) { var act = start('remove'); delegate.remove(query, endSink(act, sink)); }, find: function(key, sink) { var act = start('find'); delegate.find(key, endSink(act, sink)); }, select: function(sink, options) { var act = start('select'); var fut = afuture(); delegate.select(sink, options)(function(s) { end(act); fut.set(s); }); return fut.get; } }; } }; var ObjectToJSON = { __proto__: Visitor.create(), visitFunction: function(o) { return o.toString(); }, visitObject: function(o) { this.push({ model_: (o.model_.package ? o.model_.package + '.' : '') + o.model_.name }); this.__proto__.visitObject.call(this, o); return this.pop(); }, visitProperty: function(o, prop) { prop.propertyToJSON(this, this.top(), o); }, visitMap: function(o) { this.push({}); Visitor.visitMap.call(this, o); return this.pop(); }, visitMapElement: function(key, value) { this.top()[key] = this.visit(value); }, visitArray: function(o) { this.push([]); this.__proto__.visitArray.call(this, o); return this.pop(); }, visitArrayElement: function (arr, i) { this.top().push(this.visit(arr[i])); } }; var JSONToObject = { __proto__: ObjectToJSON.create(), visitString: function(o) { try { return o.substr(0, 9) === 'function(' ? eval('(' + o + ')') : o ; } catch (x) { console.log(x, o); return o; } }, visitObject: function(o) { var model = X.lookup(o.model_); if ( ! model ) throw new Error('Unknown Model: ' + o.model_); var obj = model.create(); // o.forEach((function(value, key) { // Workaround for crbug.com/258522 Object_forEach(o, (function(value, key) { if ( key !== 'model_' ) obj[key] = this.visit(value); }).bind(this)); return obj; }, // Substitute in-place visitArray: Visitor.visitArray, visitArrayElement: function (arr, i) { arr[i] = this.visit(arr[i]); } }; CLASS({ name: 'FilteredDAO_', extendsModel: 'foam.dao.ProxyDAO', documentation: '<p>Internal use only.</p>', properties: [ { name: 'query', required: true } ], methods: { select: function(sink, options) { return this.delegate.select(sink, options ? { __proto__: options, query: options.query ? AND(this.query, options.query) : this.query } : {query: this.query}); }, removeAll: function(sink, options) { return this.delegate.removeAll(sink, options ? { __proto__: options, query: options.query ? AND(this.query, options.query) : this.query } : {query: this.query}); }, listen: function(sink, options) { return this.SUPER(sink, options ? { __proto__: options, query: options.query ? AND(this.query, options.query) : this.query } : {query: this.query}); }, toString: function() { return this.delegate + '.where(' + this.query + ')'; } } }); CLASS({ name: 'OrderedDAO_', extendsModel: 'foam.dao.ProxyDAO', documentation: function() {/* <p>Internal use only.</p> */}, properties: [ { name: 'comparator', required: true } ], methods: { select: function(sink, options) { if ( options ) { if ( ! options.order ) options = { __proto__: options, order: this.comparator }; } else { options = {order: this.comparator}; } return this.delegate.select(sink, options); }, toString: function() { return this.delegate + '.orderBy(' + this.comparator + ')'; } } }); CLASS({ name: 'LimitedDAO_', extendsModel: 'foam.dao.ProxyDAO', documentation: function() {/* <p>Internal use only.</p> */}, properties: [ { name: 'count', required: true } ], methods: { select: function(sink, options) { if ( options ) { if ( 'limit' in options ) { options = { __proto__: options, limit: Math.min(this.count, options.limit) }; } else { options = { __proto__: options, limit: this.count }; } } else { options = { limit: this.count }; } return this.delegate.select(sink, options); }, toString: function() { return this.delegate + '.limit(' + this.count + ')'; } } }); CLASS({ name: 'SkipDAO_', extendsModel: 'foam.dao.ProxyDAO', documentation: function() {/* <p>Internal use only.</p> */}, properties: [ { name: 'skip', required: true, postSet: function() { if ( this.skip !== Math.floor(this.skip) ) console.warn('skip() called with non-integer value: ' + this.skip); } } ], methods: { select: function(sink, options) { options = options ? { __proto__: options, skip: this.skip } : { skip: this.skip }; return this.delegate.select(sink, options); }, toString: function() { return this.delegate + '.skip(' + this.skip + ')'; } } }); CLASS({ name: 'RelationshipDAO', extendsModel: 'FilteredDAO_', documentation: 'Adapts a DAO based on a Relationship.', properties: [ { name: 'relatedProperty', required: true }, { name: 'relativeID', required: true }, { name: 'query', lazyFactory: function() { return AND(NEQ(this.relatedProperty, ''), EQ(this.relatedProperty, this.relativeID)); } }, ], methods: [ function put(obj, sink) { obj[this.relatedProperty.name] = this.relativeID; this.SUPER(obj, sink); } ] }); function atxn(afunc) { return function(ret) { if ( GLOBAL.__TXN__ ) { afunc.apply(this, arguments); } else { GLOBAL.__TXN__ = {}; var a = argsToArray(arguments); a[0] = function() { GLOBAL.__TXN__ = undefined; ret(); }; afunc.apply(this, a); } }; } CLASS({ name: 'AbstractDAO', documentation: function() {/* The base for most DAO implementations, $$DOC{ref:'.'} provides basic facilities for $$DOC{ref:'.where'}, $$DOC{ref:'.limit'}, $$DOC{ref:'.skip'}, and $$DOC{ref:'.orderBy'} operations, and provides for notifications of updates through $$DOC{ref:'.listen'}. */}, requires: [ // 'FilteredDAO_', // can't require these due to cycle back to AbstractDAO. // 'LimitedDAO_', // 'SkipDAO_', // 'OrderedDAO_' ], properties: [ { name: 'daoListeners_', transient: true, hidden: true, factory: function() { return []; } } ], methods: { init: function() { arequire('FilteredDAO_'); arequire('LimitedDAO_'); arequire('SkipDAO_'); arequire('OrderedDAO_'); this.SUPER(); }, update: function(expr) { /* Applies a change to the DAO contents. */ return this.select(UPDATE(expr, this)); }, select: function(sink, options) { /* Template method. Override to copy the contents of this DAO (filtered or ordered as necessary) to sink. */ }, remove: function(query, sink) { /* Template method. Override to remove matching items and put them into sink if supplied. */ }, pipe: function(sink, options) { /* A $$DOC{ref:'.select'} followed by $$DOC{ref:'.listen'}. Dump our contents to sink, then send future changes there as well. */ sink = this.decorateSink_(sink, options, true); var fc = this.createFlowControl_(); var self = this; this.select({ put: function() { sink.put && sink.put.apply(sink, arguments); }, remove: function() { sink.remove && sink.remove.apply(sink, arguments); }, error: function() { sink.error && sink.error.apply(sink, arguments); }, eof: function() { if ( fc.stopped ) { sink.eof && sink.eof(); } else { self.listen(sink, options); } } }, options, fc); }, decorateSink_: function(sink, options, isListener, disableLimit) { if ( options ) { if ( ! disableLimit ) { if ( options.limit ) sink = limitedSink(options.limit, sink); if ( options.skip ) sink = skipSink(options.skip, sink); } if ( options.order && ! isListener ) { sink = orderedSink(options.order, sink); } if ( options.query ) { sink = predicatedSink( options.query.partialEval ? options.query.partialEval() : options.query, sink) ; } } return sink; }, createFlowControl_: function() { return { stop: function() { this.stopped = true; }, error: function(e) { this.errorEvt = e; } }; }, where: function(query) { /* Return a DAO that contains a filtered subset of this one. */ // only use X if we are an invalid instance without a this.Y return (this.Y || X).lookup('FilteredDAO_').create({query: query, delegate: this}); }, limit: function(count) { /* Return a DAO that contains a count limited subset of this one. */ return (this.Y || X).lookup('LimitedDAO_').create({count:count, delegate:this}); }, skip: function(skip) { /* Return a DAO that contains a subset of this one, skipping initial items. */ return (this.Y || X).lookup('SkipDAO_').create({skip:skip, delegate:this}); }, orderBy: function() { /* Return a DAO that contains a subset of this one, ordered as specified. */ return (this.Y || X).lookup('OrderedDAO_').create({ comparator: arguments.length == 1 ? arguments[0] : argsToArray(arguments), delegate: this }); }, listen: function(sink, options) { /* Send future changes to sink. */ this.daoListeners_.push(this.decorateSink_(sink, options, true)); }, unlisten: function(sink) { /* Stop sending updates to the given sink. */ var ls = this.daoListeners_; // if ( ! ls.length ) console.warn('Phantom DAO unlisten: ', this, sink); for ( var i = 0; i < ls.length ; i++ ) { if ( ls[i].$UID === sink.$UID ) { ls.splice(i, 1); return true; } } console.assert(! DEBUG, 'Phantom DAO unlisten: ', this, sink); }, // Default removeAll: calls select() with the same options and // calls remove() for all returned values. removeAll: function(sink, options) { /* Default $$DOC{ref:'.removeAll'}: calls $$DOC{ref:'.select'} with the same options and calls $$DOC{ref:'.remove'} for all returned values. */ var self = this; var future = afuture(); this.select({ put: function(obj) { self.remove(obj, { remove: sink && sink.remove }); } })(function() { sink && sink.eof(); future.set(); }); return future.get; }, /** * Notify all listeners of update to DAO. * @param fName the name of the method in the listeners to call. * possible values: 'put', 'remove' **/ notify_: function(fName, args) { // console.log(this.name_, ' ***** notify ', fName, ' args: ', args, ' listeners: ', this.daoListeners_); for( var i = 0 ; i < this.daoListeners_.length ; i++ ) { var l = this.daoListeners_[i]; var fn = l[fName]; if ( fn ) { // Create flow-control object args[2] = { stop: (function(fn, l) { return function() { fn(l); }; })(this.unlisten.bind(this), l), error: function(e) { /* Don't care. */ } }; try { fn.apply(l, args); } catch(err) { if ( err !== this.UNSUBSCRIBE_EXCEPTION ) { console.error('Error delivering event (removing listener): ', fName, err); } this.unlisten(l); } } } } } }); // Experimental, convert all functions into sinks Function.prototype.put = function() { this.apply(this, arguments); }; Function.prototype.remove = function() { this.apply(this, arguments); }; Function.prototype.reset = function() { this.call(this); }; //Function.prototype.error = function() { this.apply(this, arguments); }; //Function.prototype.eof = function() { this.apply(this, arguments); }; /** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function() { // Copy X.AbstractDAO methods in Array prototype var pmap = {}; for ( var key in AbstractDAO.methods ) { pmap[AbstractDAO.methods[key].name] = AbstractDAO.methods[key].code; } for ( var key in pmap ) { Object.defineProperty(Array.prototype, key, { value: pmap[key], configurable: true, writable: true }); } })(); defineLazyProperty(Array.prototype, 'daoListeners_', function() { return { value: [], configurable: true }; }); var ArraySink = { __proto__: Array.prototype, put: function(obj, sink) { this.push(obj); this.notify_('put', arguments); sink && sink.put && sink.put(obj); }, clone: function() { return this.slice().sink; }, deepClone: function() { return Array.prototype.call(this).sink; } }; MODEL0({ extendsProto: 'Array', properties: [ { name: 'dao', getter: function() { this.__proto__ = Array.prototype; return this; } }, { name: 'sink', getter: function() { this.__proto__ = ArraySink; return this; } } ], methods: { listen: AbstractDAO.getPrototype().listen, unlisten: AbstractDAO.getPrototype().unlisten, notify_: AbstractDAO.getPrototype().notify_, // Clone this Array and remove 'v' (only 1 instance) // TODO: make faster by copying in one pass, without splicing deleteF: function(v) { var a = this.clone(); for ( var i = 0 ; i < a.length ; i++ ) { if ( a[i] === v ) { a.splice(i, 1); break; } } return a; }, // Remove 'v' from this array (only 1 instance removed) // return true iff the value was removed deleteI: function(v) { for ( var i = 0 ; i < this.length ; i++ ) { if ( this[i] === v ) { this.splice(i, 1); return true; } } return false; }, // Clone this Array and remove first object where predicate 'p' returns true // TODO: make faster by copying in one pass, without splicing removeF: function(p) { var a = this.clone(); for ( var i = 0 ; i < a.length ; i++ ) { if ( p.f(a[i]) ) { a.splice(i, 1); break; } } return a; }, // Remove first object in this array where predicate 'p' returns true removeI: function(p) { for ( var i = 0 ; i < this.length ; i++ ) { if ( p.f(this[i]) ) { this.splice(i, 1); breeak; } } return this; }, pushF: function(obj) { var a = this.clone(); a.push(obj); return a; }, id: function(obj) { return obj.id || obj.$UID; }, put: function(obj, sink) { for ( var idx = 0; idx < this.length; idx++ ) { if ( this[idx].id === obj.id ) { this[idx] = obj; sink && sink.put && sink.put(obj); this.notify_('put', arguments); // sink && sink.error && sink.error('put', obj, duplicate); return; } } this.push(obj); this.notify_('put', arguments); sink && sink.put && sink.put(obj); }, find: function(query, sink) { if ( query.f ) { for ( var idx = 0 ; idx < this.length; idx++ ) { if ( query.f(this[idx]) ) { sink && sink.put && sink.put(this[idx]); return; } } } else { for ( var idx = 0 ; idx < this.length; idx++ ) { if ( this[idx].id === query ) { sink && sink.put && sink.put(this[idx]); return; } } } sink && sink.error && sink.error('find', query); }, // TODO: make this faster, should stop after finding first item. remove: function(obj, sink) { if ( ! obj ) { sink && sink.error && sink.error('missing key'); return; } var objId = obj.id; var id = (objId !== undefined && objId !== '') ? objId : obj; for ( var idx = 0 ; idx < this.length; idx++ ) { if ( this[idx].id === id ) { var rem = this.splice(idx,1)[0]; // this.notify_('remove', rem); sink && sink.remove && sink.remove(rem[0]); return; } } sink && sink.error && sink.error('remove', obj); }, removeAll: function(sink, options) { if ( ! options ) options = {}; if ( !options.query ) options.query = { f: function() { return true; } }; for (var i = 0; i < this.length; i++) { var obj = this[i]; if ( options.query.f(obj) ) { var rem = this.splice(i,1)[0]; // this.notify_('remove', [rem]); sink && sink.remove && sink.remove(rem); i--; } } sink && sink.eof && sink.eof(); return anop(); }, select: function(sink, options) { sink = sink || [].sink; var hasQuery = options && ( options.query || options.order ); var originalsink = sink; sink = this.decorateSink_(sink, options, false, ! hasQuery); // Short-circuit COUNT. if ( ! hasQuery && GLOBAL.CountExpr && CountExpr.isInstance(sink) ) { sink.count = this.length; return aconstant(originalsink); } var fc = this.createFlowControl_(); var start = Math.max(0, hasQuery ? 0 : ( options && options.skip ) || 0); var end = hasQuery ? this.length : Math.min(this.length, start + ( ( options && options.limit ) || this.length)); for ( var i = start ; i < end ; i++ ) { sink.put(this[i], null, fc); if ( fc.stopped ) break; if ( fc.errorEvt ) { sink.error && sink.error(fc.errorEvt); return aconstant(originalsink, fc.errorEvt); } } sink.eof && sink.eof(); return aconstant(originalsink); } } }); /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /* * Index Interface: * put(state, value) -> new state * remove(state, value) -> new state * removeAll(state) -> new state // TODO * plan(state, sink, options) -> {cost: int, toString: fn, execute: fn} * size(state) -> int * Add: * get(key) -> obj * update(oldValue, newValue) * * TODO: * reuse plans * add ability for indices to pre-populate data */ /** Plan indicating that there are no matching records. **/ var NOT_FOUND = { cost: 0, execute: function(_, sink, _) { return anop; }, toString: function() { return "no-match(cost=0)"; } }; /** Plan indicating that an index has no plan for executing a query. **/ var NO_PLAN = { cost: Number.MAX_VALUE, execute: function() { return anop; }, toString: function() { return "no-plan"; } }; function dump(o) { if ( Array.isArray(o) ) return '[' + o.map(dump).join(',') + ']'; return o ? o.toString() : '<undefined>'; } /** An Index which holds only a single value. **/ var ValueIndex = { put: function(s, newValue) { return newValue; }, remove: function() { return undefined; }, plan: (function() { var plan = { cost: 1, execute: function(s, sink) { sink.put(s); return anop; }, toString: function() { return 'unique'; } }; return function() { return plan; }; })(), get: function(value, key) { return value; }, select: function(value, sink, options) { if ( options ) { if ( options.query && ! options.query.f(value) ) return; if ( 'skip' in options && options.skip-- > 0 ) return; if ( 'limit' in options && options.limit-- < 1 ) return; } sink.put(value); }, selectReverse: function(value, sink, options) { this.select(value, sink, options); }, size: function(obj) { return 1; }, toString: function() { return 'value'; } }; var KEY = 0; var VALUE = 1; var SIZE = 2; var LEVEL = 3; var LEFT = 4; var RIGHT = 5; // TODO: investigate how well V8 optimizes static classes // [0 key, 1 value, 2 size, 3 level, 4 left, 5 right] /** An AATree (balanced binary search tree) Index. **/ var TreeIndex = { create: function(prop, tail) { tail = tail || ValueIndex; return { __proto__: this, prop: prop, tail: tail, selectCount: 0 }; }, /** * Bulk load an unsorted array of objects. * Faster than loading individually, and produces a balanced tree. **/ bulkLoad: function(a) { // Only safe if children aren't themselves trees if ( this.tail === ValueIndex ) { a.sort(toCompare(this.prop)); return this.bulkLoad_(a, 0, a.length-1); } var s = undefined; for ( var i = 0 ; i < a.length ; i++ ) { s = this.put(s, a[i]); } return s; }, bulkLoad_: function(a, start, end) { if ( end < start ) return undefined; var m = start + Math.floor((end-start+1) / 2); var tree = this.put(undefined, a[m]); tree[LEFT] = this.bulkLoad_(a, start, m-1); tree[RIGHT] = this.bulkLoad_(a, m+1, end); tree[SIZE] += this.size(tree[LEFT]) + this.size(tree[RIGHT]); return tree; }, // Set the value's property to be the same as the key in the index. // This saves memory by sharing objects. dedup: function(obj, value) { obj[this.prop.name] = value; }, maybeClone: function(s) { if ( s && this.selectCount > 0 ) return s.clone(); return s; }, put: function(s, newValue) { return this.putKeyValue(s, this.prop.f(newValue), newValue); }, putKeyValue: function(s, key, value) { if ( ! s ) { return [key, this.tail.put(null, value), 1, 1]; } s = this.maybeClone(s); var r = this.compare(s[KEY], key); if ( r === 0 ) { this.dedup(value, s[KEY]); s[SIZE] -= this.tail.size(s[VALUE]); s[VALUE] = this.tail.put(s[VALUE], value); s[SIZE] += this.tail.size(s[VALUE]); } else { var side = r > 0 ? LEFT : RIGHT; if ( s[side] ) s[SIZE] -= s[side][SIZE]; s[side] = this.putKeyValue(s[side], key, value); s[SIZE] += s[side][SIZE]; } return this.split(this.skew(s)); }, // input: T, a node representing an AA tree that needs to be rebalanced. // output: Another node representing the rebalanced AA tree. skew: function(s) { if ( s && s[LEFT] && s[LEFT][LEVEL] === s[LEVEL] ) { // Swap the pointers of horizontal left links. var l = this.maybeClone(s[LEFT]); s[LEFT] = l[RIGHT]; l[RIGHT] = s; this.updateSize(s); this.updateSize(l); return l; } return s; }, updateSize: function(s) { s[SIZE] = this.size(s[LEFT]) + this.size(s[RIGHT]) + this.tail.size(s[VALUE]); }, // input: T, a node representing an AA tree that needs to be rebalanced. // output: Another node representing the rebalanced AA tree. split: function(s) { if ( s && s[RIGHT] && s[RIGHT][RIGHT] && s[LEVEL] === s[RIGHT][RIGHT][LEVEL] ) { // We have two horizontal right links. Take the middle node, elevate it, and return it. var r = this.maybeClone(s[RIGHT]); s[RIGHT] = r[LEFT]; r[LEFT] = s; r[LEVEL]++; this.updateSize(s); this.updateSize(r); return r; } return s; }, remove: function(s, value) { return this.removeKeyValue(s, this.prop.f(value), value); }, removeKeyValue: function(s, key, value) { if ( ! s ) return s; s = this.maybeClone(s); var r = this.compare(s[KEY], key); if ( r === 0 ) { s[SIZE] -= this.tail.size(s[VALUE]); s[VALUE] = this.tail.remove(s[VALUE], value); // If the sub-Index still has values, then don't // delete this node. if ( s[VALUE] ) { s[SIZE] += this.tail.size(s[VALUE]); return s; } // If we're a leaf, easy, otherwise reduce to leaf case. if ( ! s[LEFT] && ! s[RIGHT] ) return undefined; var side = s[LEFT] ? LEFT : RIGHT; // TODO: it would be faster if successor and predecessor also deleted // the entry at the same time in order to prevent two traversals. // But, this would also duplicate the delete logic. var l = side === LEFT ? this.predecessor(s) : this.successor(s) ; s[KEY] = l[KEY]; s[VALUE] = l[VALUE]; s[side] = this.removeNode(s[side], l[KEY]); } else { var side = r > 0 ? LEFT : RIGHT; s[SIZE] -= this.size(s[side]); s[side] = this.removeKeyValue(s[side], key, value); s[SIZE] += this.size(s[side]); } // Rebalance the tree. Decrease the level of all nodes in this level if // necessary, and then skew and split all nodes in the new level. s = this.skew(this.decreaseLevel(s)); if ( s[RIGHT] ) { s[RIGHT] = this.skew(this.maybeClone(s[RIGHT])); if ( s[RIGHT][RIGHT] ) s[RIGHT][RIGHT] = this.skew(this.maybeClone(s[RIGHT][RIGHT])); } s = this.split(s); s[RIGHT] = this.split(this.maybeClone(s[RIGHT])); return s; }, removeNode: function(s, key) { if ( ! s ) return s; s = this.maybeClone(s); var r = this.compare(s[KEY], key); if ( r === 0 ) return s[LEFT] ? s[LEFT] : s[RIGHT]; var side = r > 0 ? LEFT : RIGHT; s[SIZE] -= this.size(s[side]); s[side] = this.removeNode(s[side], key); s[SIZE] += this.size(s[side]); return s; }, predecessor: function(s) { if ( ! s[LEFT] ) return s; for ( s = s[LEFT] ; s[RIGHT] ; s = s[RIGHT] ); return s; }, successor: function(s) { if ( ! s[RIGHT] ) return s; for ( s = s[RIGHT] ; s[LEFT] ; s = s[LEFT] ); return s; }, // input: T, a tree for which we want to remove links that skip levels. // output: T with its level decreased. decreaseLevel: function(s) { var expectedLevel = Math.min(s[LEFT] ? s[LEFT][LEVEL] : 0, s[RIGHT] ? s[RIGHT][LEVEL] : 0) + 1; if ( expectedLevel < s[LEVEL] ) { s[LEVEL] = expectedLevel; if ( s[RIGHT] && expectedLevel < s[RIGHT][LEVEL] ) { s[RIGHT] = this.maybeClone(s[RIGHT]); s[RIGHT][LEVEL] = expectedLevel; } } return s; }, get: function(s, key) { if ( ! s ) return undefined; var r = this.compare(s[KEY], key); if ( r === 0 ) return s[VALUE]; return this.get(r > 0 ? s[LEFT] : s[RIGHT], key); }, select: function(s, sink, options) { if ( ! s ) return; if ( options ) { if ( 'limit' in options && options.limit <= 0 ) return; var size = this.size(s); if ( options.skip >= size && ! options.query ) { options.skip -= size; return; } } this.select(s[LEFT], sink, options); this.tail.select(s[VALUE], sink, options); this.select(s[RIGHT], sink, options); }, selectReverse: function(s, sink, options) { if ( ! s ) return; if ( options ) { if ( 'limit' in options && options.limit <= 0 ) return; var size = this.size(s); if ( options.skip >= size ) { options.skip -= size; return; } } this.selectReverse(s[RIGHT], sink, options); this.tail.selectReverse(s[VALUE], sink, options); this.selectReverse(s[LEFT], sink, options); }, findPos: function(s, key, incl) { if ( ! s ) return 0; var r = this.compare(s[KEY], key); if ( r === 0 ) { return incl ? this.size(s[LEFT]) : this.size(s) - this.size(s[RIGHT]); } return r > 0 ? this.findPos(s[LEFT], key, incl) : this.findPos(s[RIGHT], key, incl) + this.size(s) - this.size(s[RIGHT]); }, size: function(s) { return s ? s[SIZE] : 0; }, compare: function(o1, o2) { return this.prop.compareProperty(o1, o2); }, plan: function(s, sink, options) { var query = options && options.query; if ( query === FALSE ) return NOT_FOUND; if ( ! query && CountExpr.isInstance(sink) ) { var count = this.size(s); // console.log('**************** COUNT SHORT-CIRCUIT ****************', count, this.toString()); return { cost: 0, execute: function(unused, sink, options) { sink.count += count; return anop; }, toString: function() { return 'short-circuit-count(' + count + ')'; } }; } // if ( options && options.limit != null && options.skip != null && options.skip + options.limit > this.size(s) ) return NO_PLAN; var prop = this.prop; var isExprMatch = function(model) { if ( ! model ) return undefined; if ( query ) { if ( model.isInstance(query) && query.arg1 === prop ) { var arg2 = query.arg2; query = undefined; return arg2; } if ( AndExpr.isInstance(query) ) { for ( var i = 0 ; i < query.args.length ; i++ ) { var q = query.args[i]; if ( model.isInstance(q) && q.arg1 === prop ) { query = query.clone(); query.args[i] = TRUE; query = query.partialEval(); if ( query === TRUE ) query = null; return q.arg2; } } } } return undefined; }; // if ( sink.model_ === GroupByExpr && sink.arg1 === prop ) { // console.log('**************** GROUP-BY SHORT-CIRCUIT ****************'); // TODO: // } var index = this; var arg2 = isExprMatch(GLOBAL.InExpr); if ( arg2 && // Just scan if that would be faster. Math.log(this.size(s))/Math.log(2) * arg2.length < this.size(s) ) { var keys = arg2; var subPlans = []; var results = []; var cost = 1; var newOptions = {}; if ( query ) newOptions.query = query; if ( 'limit' in options ) newOptions.limit = options.limit; if ( 'skip' in options ) newOptions.skip = options.skip; if ( 'order' in options ) newOptions.order = options.order; for ( var i = 0 ; i < keys.length ; i++) { var result = this.get(s, keys[i]); if ( result ) { var subPlan = this.tail.plan(result, sink, newOptions); cost += subPlan.cost; subPlans.push(subPlan); results.push(result); } } if ( subPlans.length == 0 ) return NOT_FOUND; return { cost: 1 + cost, execute: function(s2, sink, options) { var pars = []; for ( var i = 0 ; i < subPlans.length ; i++ ) { pars.push(subPlans[i].execute(results[i], sink, newOptions)); } return apar.apply(null, pars); }, toString: function() { return 'IN(key=' + prop.name + ', size=' + results.length + ')'; } }; } arg2 = isExprMatch(GLOBAL.EqExpr); if ( arg2 != undefined ) { var key = arg2.f(); var result = this.get(s, key); if ( ! result ) return NOT_FOUND; // var newOptions = {__proto__: options, query: query}; var newOptions = {}; if ( query ) newOptions.query = query; if ( 'limit' in options ) newOptions.limit = options.limit; if ( 'skip' in options ) newOptions.skip = options.skip; if ( 'order' in options ) newOptions.order = options.order; var subPlan = this.tail.plan(result, sink, newOptions); return { cost: 1 + subPlan.cost, execute: function(s2, sink, options) { return subPlan.execute(result, sink, newOptions); }, toString: function() { return 'lookup(key=' + prop.name + ', cost=' + this.cost + (query && query.toSQL ? ', query: ' + query.toSQL() : '') + ') ' + subPlan.toString(); } }; } arg2 = isExprMatch(GLOBAL.GtExpr); if ( arg2 != undefined ) { var key = arg2.f(); var pos = this.findPos(s, key, false); var newOptions = {skip: ((options && options.skip) || 0) + pos}; if ( query ) newOptions.query = query; if ( 'limit' in options ) newOptions.limit = options.limit; if ( 'order' in options ) newOptions.order = options.order; options = newOptions; } arg2 = isExprMatch(GLOBAL.GteExpr); if ( arg2 != undefined ) { var key = arg2.f(); var pos = this.findPos(s, key, true); var newOptions = {skip: ((options && options.skip) || 0) + pos}; if ( query ) newOptions.query = query; if ( 'limit' in options ) newOptions.limit = options.limit; if ( 'order' in options ) newOptions.order = options.order; options = newOptions; } arg2 = isExprMatch(GLOBAL.LtExpr); if ( arg2 != undefined ) { var key = arg2.f(); var pos = this.findPos(s, key, true); var newOptions = {limit: (pos - (options && options.skip) || 0)}; if ( query ) newOptions.query = query; if ( 'limit' in options ) newOptions.limit = Math.min(options.limit, newOptions.limit); if ( 'skip' in options ) newOptions.skip = options.skip; if ( 'order' in options ) newOptions.order = options.order; options = newOptions; } arg2 = isExprMatch(GLOBAL.LteExpr); if ( arg2 != undefined ) { var key = arg2.f(); var pos = this.findPos(s, key, false); var newOptions = {limit: (pos - (options && options.skip) || 0)}; if ( query ) newOptions.query = query; if ( 'limit' in options ) newOptions.limit = Math.min(options.limit, newOptions.limit); if ( 'skip' in options ) newOptions.skip = options.skip; if ( 'order' in options ) newOptions.order = options.order; options = newOptions; } var cost = this.size(s); var sortRequired = false; var reverseSort = false; if ( options && options.order ) { if ( options.order === prop ) { // sort not required } else if ( GLOBAL.DescExpr && DescExpr.isInstance(options.order) && options.order.arg1 === prop ) { // reverse-sort, sort not required reverseSort = true; } else { sortRequired = true; if ( cost != 0 ) cost *= Math.log(cost) / Math.log(2); } } if ( options && ! sortRequired ) { if ( options.skip ) cost -= options.skip; if ( options.limit ) cost = Math.min(cost, options.limit); } return { cost: cost, execute: function() { /* var o = options && (options.skip || options.limit) ? {skip: options.skip || 0, limit: options.limit || Number.MAX_VALUE} : undefined; */ if ( sortRequired ) { var a = []; index.selectCount++; index.select(s, a, {query: options.query}); index.selectCount--; a.sort(toCompare(options.order)); var skip = options.skip || 0; var limit = Number.isFinite(options.limit) ? options.limit : a.length; limit += skip; limit = Math.min(a.length, limit); for ( var i = skip; i < limit; i++ ) sink.put(a[i]); } else { // What did this do? It appears to break sorting in saturn mail /* if ( reverseSort && options && options.skip ) // TODO: temporary fix, should include range in select and selectReverse calls instead. options = { __proto__: options, skip: index.size(s) - options.skip - (options.limit || index.size(s)-options.skip) };*/ index.selectCount++; reverseSort ? index.selectReverse(s, sink, options) : index.select(s, sink, options) ; index.selectCount--; } return anop; }, toString: function() { return 'scan(key=' + prop.name + ', cost=' + this.cost + (query && query.toSQL ? ', query: ' + query.toSQL() : '') + ')'; } }; }, toString: function() { return 'TreeIndex(' + this.prop.name + ', ' + this.tail + ')'; } }; /** Case-Insensitive TreeIndex **/ var CITreeIndex = { __proto__: TreeIndex, create: function(prop, tail) { tail = tail || ValueIndex; return { __proto__: this, prop: prop, tail: tail }; }, put: function(s, newValue) { return this.putKeyValue(s, this.prop.f(newValue).toLowerCase(), newValue); }, remove: function(s, value) { return this.removeKeyValue(s, this.prop.f(value).toLowerCase(), value); } }; /** An Index for storing multi-valued properties. **/ var SetIndex = { __proto__: TreeIndex, create: function(prop, tail) { tail = tail || ValueIndex; return { __proto__: this, prop: prop, tail: tail }; }, // TODO: see if this can be done some other way dedup: function(obj, value) { // NOP, not safe to do here }, put: function(s, newValue) { var a = this.prop.f(newValue); if ( a.length ) { for ( var i = 0 ; i < a.length ; i++ ) { s = this.putKeyValue(s, a[i], newValue); } } else { s = this.putKeyValue(s, '', newValue); } return s; }, remove: function(s, value) { var a = this.prop.f(value); if ( a.length ) { for ( var i = 0 ; i < a.length ; i++ ) { s = this.removeKeyValue(s, a[i], value); } } else { s = this.removeKeyValue(s, '', value); } return s; } }; var PositionQuery = { create: function(args) { return { __proto__: this, skip: args.skip, limit: args.limit, s: args.s }; }, reduce: function(other) { var otherFinish = other.skip + other.limit; var myFinish = this.skip + this.limit; if ( other.skip > myFinish ) return null; if ( other.skip >= this.skip ) { return PositionQuery.create({ skip: this.skip, limit: Math.max(myFinish, otherFinish) - this.skip, s: this.s }); } return other.reduce(this); }, equals: function(other) { return this.skip === other.skip && this.limit === other.limit; } }; var AutoPositionIndex = { create: function(factory, mdao, networkdao, maxage) { var obj = { __proto__: this, factory: factory, maxage: maxage, dao: mdao, networkdao: networkdao, sets: [], alt: AltIndex.create() }; return obj; }, put: function(s, value) { return this.alt.put(s, value); }, remove: function(s, value) { return this.alt.remove(s, value); }, bulkLoad: function(a) { return []; }, addIndex: function(s, index) { return this; }, addPosIndex: function(s, options) { var index = PositionIndex.create( options && options.order, options && options.query, this.factory, this.dao, this.networkdao, this.queue, this.maxage); this.alt.delegates.push(index); s.push(index.bulkLoad([])); }, hasIndex: function(options) { for ( var i = 0; i < this.sets.length; i++ ) { var set = this.sets[i]; if ( set[0].equals((options && options.query) || '') && set[1].equals((options && options.order) || '') ) return true; } return false; }, plan: function(s, sink, options) { var subPlan = this.alt.plan(s, sink, options); if ( subPlan != NO_PLAN ) return subPlan; if ( ( options && options.skip != null && options.limit != null ) || CountExpr.isInstance(sink) ) { if ( this.hasIndex(options) ) return NO_PLAN; this.sets.push([(options && options.query) || '', (options && options.order) || '']); this.addPosIndex(s, options); return this.alt.plan(s, sink, options); } return NO_PLAN; } }; var PositionIndex = { create: function(order, query, factory, dao, networkdao, queue, maxage) { var obj = { __proto__: this, order: order || '', query: query || '', factory: factory, dao: dao, networkdao: networkdao.where(query).orderBy(order), maxage: maxage, queue: arequestqueue(function(ret, request) { var s = request.s; obj.networkdao .skip(request.skip) .limit(request.limit) .select()(function(objs) { var now = Date.now(); for ( var i = 0; i < objs.length; i++ ) { s[request.skip + i] = { obj: objs[i].id, timestamp: now }; s.feedback = objs[i].id; obj.dao.put(objs[i]); s.feedback = null; } ret(); }); }, undefined, 1) }; return obj; }, put: function(s, newValue) { if ( s.feedback === newValue.id ) return s; if ( this.query && ! this.query.f(newValue) ) return s; var compare = toCompare(this.order); for ( var i = 0; i < s.length; i++ ) { var entry = s[i] if ( ! entry ) continue; // TODO: This abuses the fact that find is synchronous. this.dao.find(entry.obj, { put: function(o) { entry = o; } }); // Only happens when things are put into the dao from a select on this index. // otherwise objects are removed() first from the MDAO. if ( entry.id === newValue.id ) { break; } if ( compare(entry, newValue) > 0 ) { for ( var j = s.length; j > i; j-- ) { s[j] = s[j-1]; } // If we have objects on both sides, put this one here. if ( i == 0 || s[i-1] ) s[i] = { obj: newValue.id, timestamp: Date.now() }; break; } } return s; }, remove: function(s, obj) { if ( s.feedback === obj.id ) return s; for ( var i = 0; i < s.length; i++ ) { if ( s[i] && s[i].obj === obj.id ) { for ( var j = i; j < s.length - 1; j++ ) { s[j] = s[j+1]; } break; } } return s; }, bulkLoad: function(a) { return []; }, plan: function(s, sink, options) { var order = ( options && options.order ) || ''; var query = ( options && options.query ) || ''; var skip = options && options.skip; var limit = options && options.limit; var self = this; if ( ! order.equals(this.order) || ! query.equals(this.query) ) return NO_PLAN; if ( CountExpr.isInstance(sink) ) { return { cost: 0, execute: function(s, sink, options) { if ( ! s.count ) { s.count = amemo(function(ret) { self.networkdao.select(COUNT())(function(c) { ret(c); }); }, self.maxage); } return (function(ret, count) { sink.copyFrom(count); ret(); }).ao(s.count); }, toString: function() { return 'position-index(cost=' + this.cost + ', count)'; } } } else if ( skip == undefined || limit == undefined ) { return NO_PLAN; } var threshold = Date.now() - this.maxage; return { cost: 0, toString: function() { return 'position-index(cost=' + this.cost + ')'; }, execute: function(s, sink, options) { var objs = []; var min; var max; for ( var i = 0 ; i < limit; i++ ) { var o = s[i + skip]; if ( ! o || o.timestamp < threshold ) { if ( min == undefined ) min = i + skip; max = i + skip; } if ( o ) { // TODO: Works because find is actually synchronous. // this will need to fixed if find starts using an async function. self.dao.find(o.obj, { put: function(obj) { objs[i] = obj; } }); } else { objs[i] = self.factory(); } if ( ! objs[i] ) debugger; } if ( min != undefined ) { self.queue(PositionQuery.create({ skip: min, limit: (max - min) + 1, s: s })); } for ( var i = 0; i < objs.length; i++ ) { sink.put(objs[i]); } return anop; } }; } }; var AltIndex = { // Maximum cost for a plan which is good enough to not bother looking at the rest. GOOD_ENOUGH_PLAN: 10, // put to 10 or more when not testing create: function() { return { __proto__: this, delegates: argsToArray(arguments) }; }, addIndex: function(s, index) { // Populate the index var a = [].sink; this.plan(s, a).execute(s, a); s.push(index.bulkLoad(a)); this.delegates.push(index); return this; }, bulkLoad: function(a) { for ( var i = 0 ; i < this.delegates.length ; i++ ) { this.root[i] = this.delegates[i].bulkLoad(a); } }, get: function(s, key) { return this.delegates[0].get(s[0], key); }, put: function(s, newValue) { s = s || [].sink; for ( var i = 0 ; i < this.delegates.length ; i++ ) { s[i] = this.delegates[i].put(s[i], newValue); } return s; }, remove: function(s, obj) { s = s || [].sink; for ( var i = 0 ; i < this.delegates.length ; i++ ) { s[i] = this.delegates[i].remove(s[i], obj); } return s; }, plan: function(s, sink, options) { var bestPlan; var bestPlanI = 0; // console.log('Planning: ' + (options && options.query && options.query.toSQL && options.query.toSQL())); for ( var i = 0 ; i < this.delegates.length ; i++ ) { var plan = this.delegates[i].plan(s[i], sink, options); // console.log(' plan ' + i + ': ' + plan); if ( plan.cost <= AltIndex.GOOD_ENOUGH_PLAN ) { bestPlanI = i; bestPlan = plan; break; } if ( ! bestPlan || plan.cost < bestPlan.cost ) { bestPlanI = i; bestPlan = plan; } } // console.log('Best Plan: ' + bestPlan); if ( bestPlan == undefined || bestPlan == NO_PLAN ) return NO_PLAN; return { __proto__: bestPlan, execute: function(unused, sink, options) { return bestPlan.execute(s[bestPlanI], sink, options); } }; }, size: function(obj) { return this.delegates[0].size(obj[0]); }, toString: function() { return 'Alt(' + this.delegates.join(',') + ')'; } }; var mLangIndex = { create: function(mlang) { return { __proto__: this, mlang: mlang, PLAN: { cost: 0, execute: function(s, sink, options) { sink.copyFrom(s); return anop; }, toString: function() { return 'mLangIndex(' + this.s + ')'; } } }; }, bulkLoad: function(a) { a.select(this.mlang); return this.mlang; }, put: function(s, newValue) { // TODO: Should we clone s here? That would be more // correct in terms of the purely functional interface // but maybe we can get away with it. s = s || this.mlang.clone(); s.put(newValue); return s; }, remove: function(s, obj) { // TODO: Should we clone s here? That would be more // correct in terms of the purely functional interface // but maybe we can get away with it. s = s || this.mlang.clone(); s.remove && s.remove(obj); return s; }, size: function(s) { return Number.MAX_VALUE; }, plan: function(s, sink, options) { // console.log('s'); if ( options && options.query ) return NO_PLAN; if ( sink.model_ && sink.model_.isInstance(s) && s.arg1 === sink.arg1 ) { this.PLAN.s = s; return this.PLAN; } return NO_PLAN; }, toString: function() { return 'mLangIndex(' + this.mlang + ')'; } }; /** An Index which adds other indices as needed. **/ var AutoIndex = { create: function(mdao) { return { __proto__: this, properties: { id: true }, mdao: mdao }; }, put: function(s, newValue) { return s; }, remove: function(s, obj) { return s; }, bulkLoad: function(a) { return 'auto'; }, addIndex: function(prop) { if ( GLOBAL.DescExpr && DescExpr.isInstance(prop) ) prop = prop.arg1; console.log('Adding AutoIndex : ', prop.name); this.properties[prop.name] = true; this.mdao.addIndex(prop); }, plan: function(s, sink, options) { if ( options ) { if ( options.order && Property.isInstance(options.order) && ! this.properties[options.order.name] ) { this.addIndex(options.order); } else if ( options.query ) { // TODO: check for property in query } } return NO_PLAN; }, toString: function() { return 'AutoIndex()'; } }; var MDAO = Model.create({ extendsModel: 'AbstractDAO', name: 'MDAO', label: 'Indexed DAO', properties: [ { name: 'model', type: 'Model', required: true }, { model_: 'BooleanProperty', name: 'autoIndex', defaultValue: false } ], methods: { init: function() { this.SUPER(); this.map = {}; // TODO(kgr): this doesn't support multi-part keys, but should this.index = TreeIndex.create(this.model.getProperty(this.model.ids[0])); if ( this.autoIndex ) this.addRawIndex(AutoIndex.create(this)); }, /** * Add a non-unique index * args: one or more properties **/ addIndex: function() { var props = argsToArray(arguments); // Add on the primary key(s) to make the index unique. for ( var i = 0 ; i < this.model.ids.length ; i++ ) { props.push(this.model.getProperty(this.model.ids[i])); if ( ! props[props.length - 1] ) throw "Undefined index property"; } return this.addUniqueIndex.apply(this, props); }, /** * Add a unique index * args: one or more properties **/ addUniqueIndex: function() { var index = ValueIndex; for ( var i = arguments.length-1 ; i >= 0 ; i-- ) { var prop = arguments[i]; // TODO: the index prototype should be in the property var proto = prop.type == 'Array[]' ? SetIndex : TreeIndex; index = proto.create(prop, index); } return this.addRawIndex(index); }, // TODO: name 'addIndex' and renamed addIndex addRawIndex: function(index) { // Upgrade single Index to an AltIndex if required. if ( ! /*AltIndex.isInstance(this.index)*/ this.index.delegates ) { this.index = AltIndex.create(this.index); this.root = [this.root]; } this.index.addIndex(this.root, index); return this; }, /** * Bulk load data from another DAO. * Any data already loaded into this DAO will be lost. * @arg sink (optional) eof is called when loading is complete. **/ bulkLoad: function(dao, sink) { var self = this; dao.select({ __proto__: [].sink, eof: function() { self.root = self.index.bulkLoad(this); sink && sink.eof && sink.eof(); }}); }, put: function(obj, sink) { var oldValue = this.map[obj.id]; if ( oldValue ) { this.root = this.index.put(this.index.remove(this.root, oldValue), obj); this.notify_('remove', [oldValue]); } else { this.root = this.index.put(this.root, obj); } this.map[obj.id] = obj; this.notify_('put', [obj]); sink && sink.put && sink.put(obj); }, findObj_: function(key, sink) { var obj = this.map[key]; // var obj = this.index.get(this.root, key); if ( obj ) { sink.put && sink.put(obj); } else { sink.error && sink.error('find', key); } }, find: function(key, sink) { if ( key == undefined ) { sink && sink.error && sink.error('missing key'); return; } if ( ! key.f ) { // TODO: make better test, use model this.findObj_(key, sink); return; } // How to handle multi value primary keys? var found = false; this.where(key).limit(1).select({ // ???: Is 'put' needed? put: function(obj) { found = true; sink && sink.put && sink.put(obj); }, eof: function() { if ( ! found ) sink && sink.error && sink.error('find', key); } }); }, remove: function(obj, sink) { if ( ! obj ) { sink && sink.error && sink.error('missing key'); return; } var id = (obj.id !== undefined && obj.id !== '') ? obj.id : obj; var self = this; this.find(id, { put: function(obj) { self.root = self.index.remove(self.root, obj); delete self.map[obj.id]; self.notify_('remove', [obj]); sink && sink.remove && sink.remove(obj); }, error: function() { sink && sink.error && sink.error('remove', obj); } }); }, removeAll: function(sink, options) { if (!options) options = {}; if (!options.query) options.query = TRUE; var future = afuture(); this.where(options.query).select()(function(a) { for ( var i = 0 ; i < a.length ; i++ ) { this.root = this.index.remove(this.root, a[i]); delete this.map[a[i].id]; this.notify_('remove', [a[i]]); sink && sink.remove && sink.remove(a[i]); } sink && sink.eof && sink.eof(); future.set(sink); }.bind(this)); return future.get; }, select: function(sink, options) { sink = sink || [].sink; // Clone the options to prevent 'limit' from being mutated in the original. if ( options ) options = {__proto__: options}; if ( GLOBAL.ExplainExpr && GLOBAL.ExplainExpr.isInstance(sink) ) { var plan = this.index.plan(this.root, sink.arg1, options); sink.plan = 'cost: ' + plan.cost + ', ' + plan.toString(); sink && sink.eof && sink.eof(); return aconstant(sink); } var plan = this.index.plan(this.root, sink, options); var future = afuture(); plan.execute(this.root, sink, options)( function(ret) { sink && sink.eof && sink.eof(); future.set(sink) }); return future.get; }, toString: function() { return 'MDAO(' + this.model.name + ',' + this.index + ')'; } } }); /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ /** * Used when creating PersistentContext's. * Ex. * var persistentContext = PersistentContext.create({ * dao: IDBDAO.create({model: Binding}), * predicate: NOT_TRANSIENT, * context: GLOBAL * }); * ... * persistentContext.bindObject('userInfo', UserInfo, {}); * * TODO: Make simpler to setup. **/ CLASS({ name: 'Binding', documentation: function() {/* <p>Used when creating $$DOC{ref:'PersistentContext',usePlural:true}.</p> <p><code>var persistentContext = PersistentContext.create({<br/> dao: IDBDAO.create({model: Binding}),<br/> predicate: NOT_TRANSIENT,<br/> context: GLOBAL<br/> });<br/> ...<br/> persistentContext.bindObject('userInfo', UserInfo, {});<br/> </code></p> */}, properties: [ // TODO: add support for named sub-contexts { name: 'id', hidden: true }, { name: 'value', hidden: true }, { name: 'version', defaultValue: 1, hidden: true } ] }); CLASS({ name: 'PersistentContext', documentation: function() {/* <p>Persists a set of Objects. Despite the name, this has nothing to do with $$DOC{ref:'developerDocs.Context', text:'Contexts'}.</p> */}, properties: [ { name: 'dao', label: 'DAO', type: 'DAO', hidden: true }, { name: 'context', hidden: true }, { name: 'predicate', type: 'Expr', defaultValueFn: function() { return TRUE; }, hidden: true } ], methods: { manage: function(name, obj, version) { var write = EventService.merged((function() { console.log('PersistentContext', 'updating', name); this.dao.put(this.Y.Binding.create({ id: name, value: JSONUtil.where(this.predicate).stringify(obj), version: version })); }).bind(this), undefined, this.Y); /* <p>Manage persistence for an object. Resave it in the DAO whenever it fires propertyChange events.</p> */ obj.addListener(write); write(); }, bindObjects: function(a) { // TODO: implement }, clearBinding: function(ret, name) { var self = this; self.dao.remove.ao(self.dao.find.bind(self.dao, name))(ret); }, bindObject: function(name, factory, transientValues, version) { version = version || 1; console.log('PersistentContext', 'binding', name); var future = afuture(); transientValues = transientValues || {}; if ( this.context[name] ) { future.set(this.context[name]); } else { var newinit = (function() { console.log('PersistentContext', 'newInit', name); var obj = factory.create(); obj.copyFrom(transientValues); this.context[name] = obj; this.manage(name, obj, version); future.set(obj); }).bind(this); this.dao.find(name, { put: function (binding) { if ( binding.version !== version ) { console.log('PersistentContext', 'verison mismatch', name); newinit(); return; } console.log('PersistentContext', 'existingInit', name); // var obj = JSONUtil.parse(binding.value); // var obj = JSON.parse(binding.value); try { var json = JSON.parse(binding.value); var obj = JSONUtil.mapToObj(this.Y, json); obj.copyFrom(transientValues); this.context[name] = obj; this.manage(name, obj, version); future.set(obj); } catch(e) { console.log('PersistentContext', 'existingInit serialization error', name); newinit(); } }.bind(this), error: newinit }); } return future.get; } } }); CLASS({ name: 'UserInfo', label: 'UserInfo', properties: [ { model_: 'StringProperty', name: 'email' } ] }); /** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function deferJsonP(X) { var future = afuture(); X.ajsonp = function() { var args = arguments; return function(ret) { future.get(function(f) { f.apply(undefined, args)(ret); }); }; }; return future; } // TODO: Register model for model, or fix the facade. /** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ var __DATA; (function() { // If we're running a foam binary, i/e no ModelDAO, no need to hookup the // model dao. if ( ! window.FOAM_BOOT_DIR ) return; X.ModelDAO = X.foam.core.bootstrap.BrowserFileDAO.create(); var path = document.location.pathname; path = path.substring(0, path.lastIndexOf('/')); var foamdir = new URL(window.FOAM_BOOT_DIR).pathname; foamdir = foamdir.substring(0, foamdir.lastIndexOf('/')); foamdir = foamdir.substring(0, foamdir.lastIndexOf('/')); // If this isn't FOAM's index.html // add an additional classpath for ./js/ if ( foamdir === '' || path.indexOf(foamdir) == -1 ) { X.ModelDAO = X.foam.core.bootstrap.OrDAO.create({ delegate: X.foam.core.bootstrap.BrowserFileDAO.create({ rootPath: path + '/js/' }), primary: X.ModelDAO }); } // Hookup ModelDAO callback as CLASS and __DATA global functions. var oldClass = CLASS; MODEL = CLASS = function(json) { json.model_ = 'Model'; if ( document && document.currentScript ) json.sourcePath = document.currentScript.src; if ( document && document.currentScript && document.currentScript.callback ) document.currentScript.callback(json, oldClass); else oldClass(json); }; __DATA = function(json) { if ( document && document.currentScript ) { json.sourcePath = document.currentScript.src; document.currentScript.callback && document.currentScript.callback(json, oldClass); } }; })(); CLASS({"package": "com.todomvc","name": "Controller","traits": ["foam.ui.CSSLoaderTrait"],"requires": ["foam.ui.TextFieldView","foam.ui.DAOListView","foam.dao.EasyDAO","foam.memento.WindowHashValue","com.todomvc.Todo","com.todomvc.TodoDAO","com.todomvc.TodoFilterView"],"properties": [{"name": "input","view": {"factory_": "foam.ui.TextFieldView","placeholder": "What needs to be done?"},"setter": function (text) { // This is a fake property that adds the todo when its value gets saved. if (text) { this.dao.put(this.Todo.create({text: text})); this.propertyChange('input', text, ''); } }},{"name": "dao"},{model_:"foam.core.types.DAOProperty","name": "filteredDAO","view": "foam.ui.DAOListView"},{model_:"IntProperty","name": "completedCount"},{model_:"IntProperty","name": "activeCount","postSet": function (_, c) { this.toggle = !c; }},{model_:"BooleanProperty","name": "toggle","postSet": function (_, n) { if (n === this.activeCount > 0) { this.dao.update(SET(this.Todo.COMPLETED, n)); } }},{"name": "query","view": "com.todomvc.TodoFilterView","defaultValue": {model_:"TrueExpr"},"postSet": function (_, q) { this.filteredDAO = this.dao.where(q); }},{"name": "memento","factory": function () { return this.WindowHashValue.create(); }}],"actions": [{"name": "clear","label": "Clear completed","isEnabled": function () { return this.completedCount; },"action": function () { this.dao.where(this.Todo.COMPLETED).removeAll(); }}],"methods": [{"name": "init","code": function () { this.SUPER(); this.filteredDAO = this.dao = this.TodoDAO.create({ delegate: this.EasyDAO.create({model: this.Todo, seqNo: true, daoType: 'LOCAL', name: 'todos-foam'}) }); this.dao.listen(this.onDAOUpdate); this.onDAOUpdate(); }}],"listeners": [{"name": "onDAOUpdate","code": function () { this.dao.select(GROUP_BY(this.Todo.COMPLETED, COUNT()))(function (q) { this.completedCount = q.groups[true]; this.activeCount = q.groups[false]; }.bind(this)); },"isFramed": true}],"templates": [{"name": "CSS","template": "\u000a\u0009\u0009\u0009\u0009#filters .selected { font-weight: bold; }\u000a\u0009\u0009\u0009\u0009#filters li { margin: 4px; }\u000a\u0009\u0009\u0009\u0009.actionButton-clear:disabled { display: none; }\u000a\u0009\u0009\u0009"},{"name": "toDetailHTML","template": "\u000a\u0009\u0009\u0009<section id=\"todoapp\">\u000a\u0009\u0009\u0009\u0009<header id=\"header\"><h1>todos</h1>$$input{id: 'new-todo'}</header>\u000a\u0009\u0009\u0009\u0009<section id=\"main\">\u000a\u0009\u0009\u0009\u0009\u0009$$toggle{id: 'toggle-all', showLabel: false}\u000a\u0009\u0009\u0009\u0009\u0009$$filteredDAO{tagName: 'ul', id: 'todo-list'}\u000a\u0009\u0009\u0009\u0009</section>\u000a\u0009\u0009\u0009\u0009<footer id=\"footer\">\u000a\u0009\u0009\u0009\u0009\u0009<span id=\"todo-count\">\u000a\u0009\u0009\u0009\u0009\u0009\u0009<strong>$$activeCount{mode: 'read-only'}</strong> item<%# this.data.activeCount == 1 ? '' : 's' %> left\u000a\u0009\u0009\u0009\u0009\u0009</span>\u000a\u0009\u0009\u0009\u0009\u0009$$query{id: 'filters'}\u000a\u0009\u0009\u0009\u0009\u0009$$clear{id: 'clear-completed'}\u000a\u0009\u0009\u0009\u0009</footer>\u000a\u0009\u0009\u0009</section>\u000a\u0009\u0009\u0009<footer id=\"info\">\u000a\u0009\u0009\u0009\u0009<p>Double-click to edit a todo</p>\u000a\u0009\u0009\u0009\u0009<p>Created by <a href=\"mailto:kgr@chromium.org\">Kevin Greer</a></p>\u000a\u0009\u0009\u0009\u0009<p>Part of <a href=\"http://todomvc.com\">TodoMVC</a></p>\u000a\u0009\u0009\u0009</footer>\u000a\u0009\u0009\u0009<%\u000a\u0009\u0009\u0009\u0009var f = function () { return this.completedCount + this.activeCount == 0; }.bind(this.data);\u000a\u0009\u0009\u0009\u0009this.setClass('hidden', f, 'main');\u000a\u0009\u0009\u0009\u0009this.setClass('hidden', f, 'footer');\u000a\u0009\u0009\u0009\u0009Events.relate(this.data.memento, this.queryView.text$,\u000a\u0009\u0009\u0009\u0009\u0009\u0009function (memento) {\u000a\u0009\u0009\u0009\u0009\u0009\u0009\u0009var s = memento && memento.substring(1);\u000a\u0009\u0009\u0009\u0009\u0009\u0009\u0009var t = s ? s.capitalize() : 'All';\u000a\u0009\u0009\u0009\u0009\u0009\u0009\u0009return t;\u000a\u0009\u0009\u0009\u0009\u0009\u0009},\u000a\u0009\u0009\u0009\u0009\u0009\u0009function (label) { return '/' + label.toLowerCase(); });\u000a\u0009\u0009\u0009\u0009this.addInitializer(function () {\u000a\u0009\u0009\u0009\u0009\u0009X.$('new-todo').focus();\u000a\u0009\u0009\u0009\u0009});\u000a\u0009\u0009\u0009%>\u000a\u0009\u0009\u0009"}]}) CLASS({"package": "foam.ui","name": "TextFieldView","label": "Text Field","extendsModel": "foam.ui.SimpleView","requires": ["foam.ui.AutocompleteView"],"properties": [{model_:"StringProperty","name": "name","defaultValue": "field"},{model_:"IntProperty","name": "displayWidth","defaultValue": 30},{model_:"IntProperty","name": "displayHeight","defaultValue": 1},{model_:"StringProperty","name": "type","defaultValue": "text"},{model_:"StringProperty","name": "placeholder","defaultValue": ""},{model_:"BooleanProperty","name": "onKeyMode","getter": function () { return this.updateMode === this.EACH_KEYSTROKE; },"setter": function (nu) { this.updateMode = nu ? this.EACH_KEYSTROKE : this.DONE_EDITING; },"help": "If true, value is updated on each keystroke."},{model_:"foam.core.types.StringEnumProperty","name": "updateMode","defaultValue": "DONE_EDITING","help": "Controls when the real .data is updated: on every keystroke, when the user presses enter or blurs the box, or on enter only.","choices": [["DONE_EDITING","Done editing"],["EACH_KEYSTROKE","Every keystroke"],["ENTER_ONLY","Enter only"]]},{model_:"BooleanProperty","name": "escapeHTML","help": "If true, HTML content is escaped in display mode.","defaultValue": true},{model_:"StringProperty","name": "mode","defaultValue": "read-write","view": {"factory_": "foam.ui.ChoiceView","choices": ["read-only","read-write","final"]}},{model_:"BooleanProperty","name": "required"},{model_:"StringProperty","name": "pattern"},{"name": "domValue","hidden": true},{"name": "data"},{model_:"StringProperty","name": "readWriteTagName","hidden": true,"defaultValueFn": function () { return this.displayHeight === 1 ? 'input' : 'textarea'; }},{model_:"BooleanProperty","name": "autocomplete","defaultValue": true},{"name": "autocompleter"},{"name": "autocompleteView"}],"constants": [{"name": "ESCAPE","value": ["escape"]},{"name": "DONE_EDITING","value": "DONE_EDITING"},{"name": "EACH_KEYSTROKE","value": "EACH_KEYSTROKE"},{"name": "ENTER_ONLY","value": "ENTER_ONLY"}],"methods": [{"name": "toHTML","code": function () { /* Selects read-only versus read-write DOM output */ return this.mode === 'read-write' ? this.toReadWriteHTML() : this.toReadOnlyHTML() ; }},{"name": "toReadWriteHTML","code": function () { /* Supplies the correct element for read-write mode */ var str = '<' + this.readWriteTagName + ' id="' + this.id + '"'; str += ' type="' + this.type + '" ' + this.cssClassAttr(); this.on('click', this.onClick, this.id); str += this.readWriteTagName === 'input' ? ' size="' + this.displayWidth + '"' : ' rows="' + this.displayHeight + '" cols="' + this.displayWidth + '"'; if ( this.required ) str += ' required'; if ( this.pattern ) str += ' pattern="' + this.pattern + '"'; str += this.extraAttributes(); str += ' name="' + this.name + '">'; str += '</' + this.readWriteTagName + '>'; return str; }},{"name": "extraAttributes","code": function () { return ''; }},{"name": "toReadOnlyHTML","code": function () { /* Supplies the correct element for read-only mode */ var self = this; this.setClass('placeholder', function() { return self.data === ''; }, this.id); return this.displayHeight === 1 ? '<' + this.tagName + ' id="' + this.id + '"' + this.cssClassAttr() + ' name="' + this.name + '"></' + this.tagName + '>' : '<textarea readonly id="' + this.id + '"' + this.cssClassAttr() + ' name="' + this.name + '" rows="' + this.displayHeight + '" cols="' + this.displayWidth + '"></textarea>' ; }},{"name": "setupAutocomplete","code": function () { /* Initializes autocomplete, if $$DOC{ref:'.autocomplete'} and $$DOC{ref:'.autocompleter'} are set. */ if ( ! this.autocomplete || ! this.autocompleter ) return; var view = this.autocompleteView = this.AutocompleteView.create({ autocompleter: this.autocompleter, target: this }); this.bindAutocompleteEvents(view); }},{"name": "onAutocomplete","code": function (data) { this.data = data; }},{"name": "bindAutocompleteEvents","code": function (view) { this.$.addEventListener('blur', function() { // Notify the autocomplete view of a blur, it can decide what to do from there. view.publish('blur'); }); this.$.addEventListener('input', (function() { view.autocomplete(this.textToValue(this.$.value)); }).bind(this)); this.$.addEventListener('focus', (function() { view.autocomplete(this.textToValue(this.$.value)); }).bind(this)); }},{"name": "initHTML","code": function () { if ( ! this.$ ) return; this.SUPER(); if ( this.mode === 'read-write' ) { if ( this.placeholder ) this.$.placeholder = this.placeholder; if ( this.updateMode === this.EACH_KEYSTROKE ) { this.domValue = DomValue.create(this.$, 'input'); } else if ( this.updateMode === this.DONE_EDITING ) { this.domValue = DomValue.create(this.$, 'change'); } else { this.domValue = this.OnEnterValue.create({ element: this.$ }); } // In KeyMode we disable feedback to avoid updating the field // while the user is still typing. Then we update the view // once they leave(blur) the field. Events.relate( this.data$, this.domValue, this.valueToText.bind(this), this.textToValue.bind(this), this.updateMode === this.EACH_KEYSTROKE); if ( this.updateMode === this.EACH_KEYSTROKE ) this.$.addEventListener('blur', this.onBlur); this.$.addEventListener('keydown', this.onKeyDown); this.setupAutocomplete(); } else { this.domValue = DomValue.create( this.$, 'undefined', this.escapeHTML ? 'textContent' : 'innerHTML'); Events.map( this.data$, this.domValue, this.valueToText.bind(this)) } }},{"name": "textToValue","code": function (text) { /* Passthrough */ return text; }},{"name": "valueToText","code": function (value) { /* Filters for read-only mode */ if ( this.mode === 'read-only' ) return (value === '') ? this.placeholder : value; return value; }},{"name": "destroy","code": function ( isParentDestroyed ) { /* Unlinks key handler. */ this.SUPER(isParentDestroyed); Events.unlink(this.domValue, this.data$); }}],"listeners": [{"name": "onKeyDown","code": function (e) { if ( e.keyCode == 27 /* ESCAPE KEY */ ) { this.domValue.set(this.data); this.publish(this.ESCAPE); } else { this.publish(['keydown'], e); } }},{"name": "onBlur","code": function (e) { if ( this.domValue.get() !== this.data ) this.domValue.set(this.data); }},{"name": "onClick","code": function (e) { this.$ && this.$.focus(); }}],"models": [{"name": "OnEnterValue","properties": [{"name": "element"},{"name": "listeners","factory": function () { return []; }}],"methods": [{"name": "get","code": function get() { return this.element.value; }},{"name": "set","code": function set(value) { if ( this.get() !== value ) this.element.value = value; }},{"name": "addListener","code": function addListener(listener) { if ( ! listener ) return; if ( this.listeners.length === 0 ) this.element.addEventListener('keydown', this.onKeyDown); this.listeners.push(listener); }},{"name": "removeListener","code": function removeListener(listener) { var index = this.listeners.indexOf(listener); if ( index >= 0 ) this.listeners.splice(i, 1); }},{"name": "fireListeners","code": function fireListeners(e) { for (var i = 0; i < this.listeners.length; i++) { this.listeners[i](e); } }}],"listeners": [{"name": "onKeyDown","code": function (e) { if ( e.keyCode === 13 ) { this.fireListeners(e); } }}]}]}) CLASS({"package": "foam.ui","name": "AutocompleteView","extendsModel": "foam.ui.PopupView","properties": [{"name": "closeTimeout"},{"name": "autocompleter"},{"name": "completer"},{"name": "current"},{model_:"IntProperty","name": "closeTime","units": "ms","help": "Time to delay the actual close on a .close call.","defaultValue": 200},{"name": "view","postSet": function (prev, v) { if ( prev ) { prev.data$.removeListener(this.complete); prev.choices$.removeListener(this.choicesUpdate); } v.data$.addListener(this.complete); v.choices$.addListener(this.choicesUpdate); }},{"name": "target","postSet": function (prev, v) { prev && prev.unsubscribe(['keydown'], this.onKeyDown); v.subscribe(['keydown'], this.onKeyDown); }},{"name": "maxHeight","defaultValue": 400},{"name": "className","defaultValue": "autocompletePopup"}],"methods": [{"name": "autocomplete","code": function (partial) { if ( ! this.completer ) { var proto = this.X.lookup(this.autocompleter); this.completer = proto.create(null, this.Y); } if ( ! this.view ) { this.view = this.makeView(); } this.current = partial; this.open(this.target); this.completer.autocomplete(partial); }},{"name": "makeView","code": function () { return this.X.ChoiceListView.create({ dao: this.completer.autocompleteDao$Proxy, extraClassName: 'autocomplete', orientation: 'vertical', mode: 'final', objToChoice: this.completer.f, useSelection: true }, this.Y); }},{"name": "init","code": function (args) { this.SUPER(args); this.subscribe('blur', (function() { this.close(); }).bind(this)); }},{"name": "open","code": function (e, opt_delay) { if ( this.closeTimeout ) { this.X.clearTimeout(this.closeTimeout); this.closeTimeout = 0; } if ( this.$ ) { this.position(this.$.firstElementChild, e.$ || e); return; } var parentNode = e.$ || e; var document = parentNode.ownerDocument; console.assert( this.X.document === document, 'X.document is not global document'); var div = document.createElement('div'); var window = document.defaultView; console.assert( this.X.window === window, 'X.window is not global window'); parentNode.insertAdjacentHTML('afterend', this.toHTML().trim()); this.position(this.$.firstElementChild, parentNode); this.initHTML(); }},{"name": "close","code": function (opt_now) { if ( opt_now ) { if ( this.closeTimeout ) { this.X.clearTimeout(this.closeTimeout); this.closeTimeout = 0; } this.SUPER(); return; } if ( this.closeTimeout ) return; var realClose = this.SUPER; var self = this; this.closeTimeout = this.X.setTimeout(function() { self.closeTimeout = 0; realClose.call(self); }, this.closeTime); }},{"name": "position","code": function (div, parentNode) { var document = parentNode.ownerDocument; var pos = findPageXY(parentNode); var pageWH = [document.firstElementChild.offsetWidth, document.firstElementChild.offsetHeight]; if ( pageWH[1] - (pos[1] + parentNode.offsetHeight) < (this.height || this.maxHeight || 400) ) { div.style.bottom = parentNode.offsetHeight; document.defaultView.innerHeight - pos[1]; } if ( pos[2].offsetWidth - pos[0] < 600 ) div.style.left = 600 - pos[2].offsetWidth; else div.style.left = -parentNode.offsetWidth; if ( this.width ) div.style.width = this.width + 'px'; if ( this.height ) div.style.height = this.height + 'px'; if ( this.maxWidth ) { div.style.maxWidth = this.maxWidth + 'px'; div.style.overflowX = 'auto'; } if ( this.maxHeight ) { div.style.maxHeight = this.maxHeight + 'px'; div.style.overflowY = 'auto'; } }}],"listeners": [{"name": "onKeyDown","code": function (_,_,e) { if ( ! this.view ) return; if ( e.keyCode === 38 /* arrow up */ ) { this.view.index--; this.view.scrollToSelection(this.$); e.preventDefault(); } else if ( e.keyCode === 40 /* arrow down */ ) { this.view.index++; this.view.scrollToSelection(this.$); e.preventDefault(); } else if ( e.keyCode === 13 /* enter */ ) { this.view.commit(); e.preventDefault(); } }},{"name": "complete","code": function () { this.target.onAutocomplete(this.view.data); this.view = this.makeView(); this.close(true); }},{"name": "choicesUpdate","code": function () { if ( this.view && ( this.view.choices.length === 0 || ( this.view.choices.length === 1 && this.view.choices[0][1] === this.current ) ) ) { this.close(true); } }}],"templates": [{"name": "toHTML","template": "\u000a <span id=\"<%= this.id %>\" style=\"position:relative\"><div <%= this.cssClassAttr() %> style=\"position:absolute\"><%= this.view %></div></span>\u000a "}],"help": "Default autocomplete popup."}) CLASS({"package": "foam.ui","name": "PopupView","extendsModel": "foam.ui.SimpleView","properties": [{"name": "view","type": "foam.ui.View"},{"name": "x"},{"name": "y"},{"name": "width","defaultValue": ""},{"name": "maxWidth","defaultValue": ""},{"name": "maxHeight","defaultValue": ""},{"name": "height","defaultValue": ""}],"methods": [{"name": "open","code": function (_, opt_delay) { if ( this.$ ) return; var document = this.X.document; var div = document.createElement('div'); div.style.left = this.x + 'px'; div.style.top = this.y + 'px'; if ( this.width ) div.style.width = this.width + 'px'; if ( this.height ) div.style.height = this.height + 'px'; if ( this.maxWidth ) div.style.maxWidth = this.maxWidth + 'px'; if ( this.maxHeight ) div.style.maxHeight = this.maxHeight + 'px'; div.style.position = 'absolute'; div.id = this.id; div.innerHTML = this.view.toHTML(); document.body.appendChild(div); this.view.initHTML(); }},{"name": "close","code": function () { this.$ && this.$.remove(); }},{"name": "destroy","code": function ( isParentDestroyed ) { this.SUPER(isParentDestroyed); this.close(); this.view.destroy(); }}]}) CLASS({"package": "foam.ui","name": "SimpleView","extendsModel": "foam.ui.BaseView","traits": ["foam.ui.HTMLViewTrait"],"requires": ["Property"],"exports": ["propertyViewProperty"],"properties": [{"name": "propertyViewProperty","type": "Property","defaultValueFn": function () { return this.Property.DETAIL_VIEW; }}]}) CLASS({"package": "foam.ui","name": "HTMLViewTrait","label": "HTMLView","requires": ["foam.input.touch.GestureTarget","foam.ui.ActionBorder","foam.ui.PropertyView","foam.ui.AsyncLoadingView"],"properties": [{"name": "id","label": "Element ID","type": "String","factory": function () { return this.instance_.id || this.nextID(); }},{model_:"foam.core.types.DocumentInstallProperty","name": "installCSS","documentInstallFn": function (X) { for ( var i = 0 ; i < this.model_.templates.length ; i++ ) { var t = this.model_.templates[i]; if ( t.name === 'CSS' ) { t.futureTemplate(function() { X.addStyle(this.CSS()); }.bind(this)); return; } } }},{"name": "shortcuts","type": "Array[Shortcut]","factory": function () { return []; }},{"name": "$","mode": "read-only","hidden": true,"getter": function () { return this.X.document.getElementById(this.id); },"setter": function () { debugger; },"help": "DOM Element."},{"name": "tagName","defaultValue": "span"},{"name": "className","defaultValue": "","help": "CSS class name(s), space separated."},{"name": "tooltip"},{"name": "tabIndex"},{"name": "extraClassName","defaultValue": ""},{"name": "propertyViewProperty","type": "Property","defaultValueFn": function () { return this.X.Property.VIEW; }},{"name": "initializers_","factory": function () { return []; }},{"name": "destructors_","factory": function () { return []; }},{model_:"BooleanProperty","name": "showActions","postSet": function (oldValue, showActions) { // TODO: No way to remove the decorator. if ( ! oldValue && showActions ) { this.addDecorator(this.ActionBorder.create()); } },"defaultValue": false},{"name": "minWidth","defaultValue": 300},{"name": "minHeight","defaultValue": 40},{"name": "preferredWidth","defaultValue": 400},{"name": "preferredHeight","defaultValue": 40},{"name": "maxWidth","defaultValue": 10000},{"name": "maxHeight","defaultValue": 40}],"constants": [{"name": "KEYPRESS_CODES","value": {"8": true,"33": true,"34": true,"37": true,"38": true,"39": true,"40": true}},{"name": "ON_HIDE","value": ["onHide"]},{"name": "ON_SHOW","value": ["onShow"]}],"methods": [{"name": "strToHTML","code": function (str) { /* Escape the string to make it HTML safe. */ return XMLUtil.escape(str.toString()) }},{"name": "cssClassAttr","code": function () { /* Returns the full CSS class to use for the $$DOC{ref:'foam.ui.View'} DOM element. */ if ( ! this.className && ! this.extraClassName ) return ''; var s = ' class="'; if ( this.className ) { s += this.className if ( this.extraClassName ) s += ' '; } if ( this.extraClassName ) s += this.extraClassName; return s + '"'; }},{"name": "bindSubView","code": function (view, prop) { /* Bind a sub-$$DOC{ref:'foam.ui.View'} to a $$DOC{ref:'Property'} of this. */ view.setValue(this.propertyValue(prop.name)); }},{"name": "focus","code": function () { /* Cause the view to take focus. */ if ( this.$ && this.$.focus ) this.$.focus(); }},{"name": "addChild","code": function (child) { /* Maintains the tree structure of $$DOC{ref:'foam.ui.View',usePlural:true}. When a sub-$$DOC{ref:'foam.ui.View'} is created, add it to the tree with this method. */ // Checked needed for legacy CViews, remove once they're gone. if ( child.toView_ ) child = child.toView_(); // Check prevents duplicate addChild() calls, // which can happen when you use creatView() to create a sub-view (and it calls addChild) // and then you write the View using TemplateOutput (which also calls addChild). // That should all be cleaned up and all outputHTML() methods should use TemplateOutput. if ( this.children.indexOf(child) != -1 ) return; return this.SUPER(child); }},{"name": "addShortcut","code": function (key, callback, context) { /* Add a keyboard shortcut. */ this.shortcuts.push([key, callback, context]); }},{"name": "nextID","code": function () { /* Convenience method to return unique DOM element ids. */ return "view" + (arguments.callee._nextId = (arguments.callee._nextId || 0) + 1); }},{"name": "addInitializer","code": function (f) { /* Adds a DOM initializer */ this.initializers_.push(f); }},{"name": "addDestructor","code": function (f) { /* Adds a DOM destructor. */ this.destructors_.push(f); }},{"name": "tapClick","code": function () { }},{"name": "resize","code": function () { /* Call when you've changed your size to allow for the possibility of relayout. */ var e = this.X.document.createEvent('Event'); e.initEvent('resize', true, true); if ( this.$ ) this.X.window.getComputedStyle(this.$); this.X.window.dispatchEvent(e); }},{"name": "on","code": function (event, listener, opt_id) { /* <p>To create DOM event handlers, use this method to set up your listener:</p> <p><code>this.on('click', this.myListener);</code></p> */ opt_id = opt_id || this.nextID(); listener = listener.bind(this); if ( event === 'click' && this.X.gestureManager ) { var self = this; var manager = this.X.gestureManager; var target = this.GestureTarget.create({ containerID: opt_id, handler: { tapClick: function(pointMap) { // Create a fake event. return listener({ preventDefault: function() { }, stopPropagation: function() { }, pointMap: pointMap }); } }, gesture: 'tap' }); manager.install(target); this.addDestructor(function() { manager.uninstall(target); }); return opt_id; } this.addInitializer(function() { var e = this.X.$(opt_id); // if ( ! e ) console.log('Error Missing element for id: ' + opt_id + ' on event ' + event); if ( e ) e.addEventListener(event, listener, false); }.bind(this)); return opt_id; }},{"name": "setAttribute","code": function (attributeName, valueFn, opt_id) { /* Set a dynamic attribute on the DOM element. */ opt_id = opt_id || this.nextID(); valueFn = valueFn.bind(this); this.addInitializer(function() { this.X.dynamic(valueFn, function() { var e = this.X.$(opt_id); if ( ! e ) throw EventService.UNSUBSCRIBE_EXCEPTION; var newValue = valueFn(e.getAttribute(attributeName)); if ( newValue == undefined ) e.removeAttribute(attributeName); else e.setAttribute(attributeName, newValue); }.bind(this)) }.bind(this)); }},{"name": "setClass","code": function (className, predicate, opt_id) { /* Set a dynamic CSS class on the DOM element. */ opt_id = opt_id || this.nextID(); predicate = predicate.bind(this); this.addInitializer(function() { this.addDestructor( this.X.dynamic( predicate, function() { var e = this.X.$(opt_id); if ( ! e ) throw EventService.UNSUBSCRIBE_EXCEPTION; DOM.setClass(e, className, predicate()); }.bind(this) ).destroy ); }.bind(this)); return opt_id; }},{"name": "setClasses","code": function (map, opt_id) { /* Set a map of dynamic CSS classes on the DOM element. Mapped as className: predicate.*/ opt_id = opt_id || this.nextID(); var keys = Objects.keys(map); for ( var i = 0 ; i < keys.length ; i++ ) { this.setClass(keys[i], map[keys[i]], opt_id); } return opt_id; }},{"name": "insertInElement","code": function (name) { /* Insert this View's toHTML into the Element of the supplied name. */ var e = this.X.$(name); e.innerHTML = this.toHTML(); this.initHTML(); }},{"name": "write","code": function (document) { /* Write the View's HTML to the provided document and then initialize. */ var html = this.toHTML(); document.body.insertAdjacentHTML('beforeend', html); this.initHTML(); }},{"name": "updateHTML","code": function () { /* Cause the HTML content to be recreated using a call to $$DOC{ref:'.toInnerHTML'}. */ if ( ! this.$ ) return; this.destroy(); this.construct(); }},{"name": "construct","code": function () { /* rebuilds the children of the view */ this.SUPER(); this.generateContent(); }},{"name": "generateContent","code": function () { /* by default, uses toInnerHTML() to generate content. Override to do something else. */ if ( ! this.$ ) return; this.$.innerHTML = this.toInnerHTML(); this.initInnerHTML(); }},{"name": "toInnerHTML","code": function () { /* <p>In most cases you can override this method to provide all of your HTML content. Calling $$DOC{ref:'.updateHTML'} will cause this method to be called again, regenerating your content. $$DOC{ref:'Template',usePlural:true} are usually called from here, or you may create a $$DOC{ref:'.toInnerHTML'} $$DOC{ref:'Template'}.</p> <p>If you are generating your content here, you may also need to override $$DOC{ref:'.initInnerHTML'} to create event handlers such as <code>this.on('click')</code>. */ return ''; }},{"name": "toHTML","code": function () { /* Generates the complete HTML content of this view, including outermost element. This element is managed by $$DOC{ref:'foam.ui.View'}, so in most cases you should use $$DOC{ref:'.toInnerHTML'} to generate your content. */ this.invokeDestructors(); return '<' + this.tagName + ' id="' + this.id + '"' + this.cssClassAttr() + '>' + this.toInnerHTML() + '</' + this.tagName + '>'; }},{"name": "initHTML","code": function () { /* This must be called once after your HTML content has been inserted into the DOM. Calling $$DOC{ref:'.updateHTML'} will automatically call $$DOC{ref:'.initHTML'}. */ this.initInnerHTML(); this.initKeyboardShortcuts(); this.maybeInitTooltip(); }},{"name": "maybeInitTooltip","code": function () { if ( ! this.tooltip || ! this.$ ) return; this.$.addEventListener('mouseenter', this.openTooltip); this.$.addEventListener('mouseleave', this.closeTooltip); }},{"name": "initInnerHTML","code": function () { /* Initialize this View and all of it's children. Usually just call $$DOC{ref:'.initHTML'} instead. When implementing a new $$DOC{ref:'foam.ui.View'} and adding listeners (including <code>this.on('click')</code>) that will be destroyed each time $$DOC{ref:'.toInnerHTML'} is called, you will have to override this $$DOC{ref:'Method'} and add them here. */ // This mostly involves attaching listeners. // Must be called activate a view after it has been added to the DOM. this.invokeInitializers(); this.initChildren(); }},{"name": "initChildren","code": function () { /* Initialize all of the children. Usually just call $$DOC{ref:'.initHTML'} instead. */ if ( this.children ) { // init children for ( var i = 0 ; i < this.children.length ; i++ ) { // console.log(i, 'init child: ' + this.children[i]); try { this.children[i].initHTML && this.children[i].initHTML(); } catch (x) { console.log('Error on View.child.initHTML', x, x.stack); } } } }},{"name": "invokeInitializers","code": function () { /* Calls all the DOM $$DOC{ref:'.initializers_'}. */ for ( var i = 0 ; i < this.initializers_.length ; i++ ) this.initializers_[i](); this.initializers_ = []; }},{"name": "invokeDestructors","code": function () { /* Calls all the DOM $$DOC{ref:'.destructors_'}. */ for ( var i = 0; i < this.destructors_.length; i++ ) this.destructors_[i](); this.destructors_ = []; }},{"name": "evtToCharCode","code": function (evt) { /* Maps an event keycode to a string */ var s = ''; if ( evt.altKey ) s += 'alt-'; if ( evt.ctrlKey ) s += 'ctrl-'; if ( evt.shiftKey && evt.type === 'keydown' ) s += 'shift-'; if ( evt.metaKey ) s += 'meta-'; s += String.fromCharCode(evt.type === 'keydown' ? evt.which : evt.charCode); return s; }},{"name": "initKeyboardShortcuts","code": function () { /* Initializes keyboard shortcuts. */ var keyMap = {}; var found = false; var self = this; function init(actions, opt_value) { actions.forEach(function(action) { for ( var j = 0 ; j < action.keyboardShortcuts.length ; j++ ) { var key = action.keyboardShortcuts[j]; // Treat single character strings as a character to be recognized if ( typeof key === 'number' ) key = String.fromCharCode(key); keyMap[key] = opt_value ? function() { action.maybeCall(self.X, opt_value.get()); } : action.maybeCall.bind(action, self.X, self) ; found = true; } }); } init(this.model_.actions); if ( this.data && this.data.model_ && this.data.model_.actions.length ) init(this.data.model_.actions, this.data$); if ( found ) { // console.log('initKeyboardShortcuts ', this.name_, this.data && this.data.model_ && this.data.model_.name ); console.assert(this.$, 'View must define outer id when using keyboard shortcuts: ' + this.name_); this.keyMap_ = keyMap; this.$.parentElement.addEventListener('keydown', this.onKeyboardShortcut); this.$.parentElement.addEventListener('keypress', this.onKeyboardShortcut); } }},{"name": "destroy","code": function ( isParentDestroyed ) { /* Cleans up the DOM when regenerating content. You should call this before creating new HTML in your $$DOC{ref:'.toInnerHTML'} or $$DOC{ref:'.toHTML'}. */ // TODO: remove listeners this.invokeDestructors(); this.SUPER(isParentDestroyed); delete this.instance_.$; }},{"name": "close","code": function () { /* Call when permanently closing the $$DOC{ref:'foam.ui.View'}. */ this.$ && this.$.remove(); this.destroy(); this.publish('closed'); }},{"name": "rectOnPage","code": function () { /* Computes the XY coordinates of the given node relative to the containing elements.</p> <p>TODO: Check browser compatibility. */ var node = this.$; var x = 0; var y = 0; var parent; var rect = this.$.getBoundingClientRect(); while ( node ) { parent = node; x += node.offsetLeft; y += node.offsetTop; node = node.offsetParent; } return { top: y, left: x, right: x+rect.width, bottom: y+rect.height, width: rect.width, height: rect.height }; }},{"name": "rectOnViewport","code": function () { /* Computes the XY coordinates of this view relative to the browser viewport. */ return this.$.getBoundingClientRect(); }},{"name": "viewportOnPage","code": function () { var bodyRect = this.X.document.documentElement.getBoundingClientRect(); var vpSize = this.viewportSize(); return { left: -bodyRect.left, top: -bodyRect.top, width: vpSize.width, height: vpSize.height, right: -bodyRect.left + vpSize.width, bottom: -bodyRect.top + vpSize.height }; }},{"name": "viewportSize","code": function () { /* returns the rect of the current viewport, relative to the page. */ return { height: (window.innerHeight || this.X.document.documentElement.clientHeight), width: (window.innerWidth || this.X.document.documentElement.clientWidth) }; }},{"name": "createView","code": function (prop, opt_args) { /* Creates a sub-$$DOC{ref:'foam.ui.View'} from $$DOC{ref:'Property'} info. */ var X = ( opt_args && opt_args.X ) || this.Y; var v = this.PropertyView.create({id: (this.nextID ? this.nextID() : this.id) +'PROP', prop: prop, copyFrom: opt_args}, X); this[prop.name + 'View'] = v.view; return v; }},{"name": "removeChild","code": function (child) { if ( this.PropertyView.isInstance(child) && child.prop ) { delete this[child.prop.name + 'View']; } this.SUPER(child); }},{"name": "createRelationshipView","code": function (r, opt_args) { if ( opt_args.model_ ) { // if a model is specified, switch to normal PropertyView path return this.createView(r, opt_args); } var X = ( opt_args && opt_args.X ) || this.Y; var v = this.AsyncLoadingView.create({ id: this.nextID(), name: r.name, model: 'foam.ui.RelationshipView', args: { relationship: r }, copyFrom: opt_args }, X); if ( v.view ) { v = v.view; } this[r.name + 'View'] = v; return v; }},{"name": "createActionView","code": function (action, opt_args) { /* Creates a sub-$$DOC{ref:'foam.ui.View'} from $$DOC{ref:'Property'} info specifically for $$DOC{ref:'Action',usePlural:true}. */ var X = ( opt_args && opt_args.X ) || this.Y; var modelName = opt_args && opt_args.model_ ? opt_args.model_ : 'foam.ui.ActionButton' ; var v = this.AsyncLoadingView.create({ id: this.nextID(), name: action.name, model: modelName, args: { action: action }, copyFrom: opt_args }, X); if ( v.view ) { v = v.view; } this[action.name + 'View'] = v; return v; }},{"name": "createTemplateView","code": function (name, opt_args) { /* Used by the $$DOC{ref:'Template',text:'$$propName'} sub-$$DOC{ref:'foam.ui.View'} creation tag in $$DOC{ref:'Template',usePlural:true}. */ var args = opt_args || {}; var X = this.Y; // Look for the property on our data first var myData = this.data$; if ( myData && myData.value && myData.value.model_ ) { var o = myData.value.model_.getFeature(name); if ( o ) { var v; if ( Action.isInstance(o) ) v = this.createActionView(o, args); else if ( Relationship.isInstance(o) ) v = this.createRelationshipView(o, args); else v = this.createView(o, args); // link data and add child view this.addDataChild(v); return v; } } // fallback to check our own properties var o = this.model_.getFeature(name); if ( ! o ) throw 'Unknown View Name: ' + name; var v; if ( Action.isInstance(o) ) v = this.createActionView(o, args); else if ( Relationship.isInstance(o) ) v = this.createRelationshipView(o, args); else v = this.createView(o, args); // set this-as-data and add child view this.addSelfDataChild(v); return v; }},{"name": "dynamicTag","code": function (tagName, f) { /* Creates a dynamic HTML tag whose content will be automatically updated. */ var id = this.nextID(); this.addInitializer(function() { this.X.dynamic(function() { var html = f(); var e = this.X.$(id); if ( e ) e.innerHTML = html; }.bind(this)); }.bind(this)); return '<' + tagName + ' id="' + id + '"></' + tagName + '>'; }}],"listeners": [{"name": "openTooltip","code": function (e) { console.assert(! this.tooltip_, 'Tooltip already defined'); arequire('foam.ui.Tooltip')(function(Tooltip) { this.tooltip_ = Tooltip.create({ text: this.tooltip, target: this.$ }, this.Y); }.bind(this)); }},{"name": "closeTooltip","code": function (e) { if ( this.tooltip_ ) { this.tooltip_.close(); this.tooltip_ = null; } }},{"name": "onKeyboardShortcut","code": function (evt) { // console.log(evt); if ( evt.type === 'keydown' && ! this.KEYPRESS_CODES[evt.which] ) return; var action = this.keyMap_[this.evtToCharCode(evt)]; if ( action ) { action(); evt.preventDefault(); evt.stopPropagation(); } }}]}) CLASS({"package": "foam.input.touch","name": "GestureTarget","properties": [{"name": "id"},{"name": "gesture","help": "The name of the gesture to be tracked."},{"name": "containerID","help": "The containing DOM node's ID. Used for checking what inputs are within which gesture targets."},{"name": "getElement","defaultValue": function () { return this.X.$(this.containerID); },"help": "Function to retrieve the element this gesture is attached to. Defaults to $(containerID)."},{"name": "handler","help": "The target for the gesture's events, after it has been recognized."}],"help": "Created by each view that wants to receive gestures."}) CLASS({"package": "foam.ui","name": "ActionBorder","methods": [{"name": "toHTML","code": function (border, delegate, args) { var str = ""; str += delegate.apply(this, args); str += '<div class="actionToolbar">'; // Actions on the View, are bound to the view var actions = this.model_.actions; for ( var i = 0 ; i < actions.length; i++ ) { var v = this.createActionView(actions[i]); //v.data = this; this.addSelfDataChild(v); str += ' ' + v.toView_().toHTML() + ' '; } // This is poor design, we should defer to the view and polymorphism // to make the distinction. if ( this.X.lookup('foam.ui.DetailView').isInstance(this) ) { // Actions on the data are bound to the data actions = this.model.actions; for ( var i = 0 ; i < actions.length; i++ ) { var v = this.createActionView(actions[i]); //v.data$ = this.data$; this.addDataChild(v); str += ' ' + v.toView_().toHTML() + ' '; } } str += '</div>'; return str; }}]}) CLASS({"package": "foam.ui","name": "PropertyView","extendsModel": "foam.ui.AsyncLoadingView","properties": [{"name": "prop","type": "Property","postSet": function (old, nu) { if ( old && this.bound_ ) this.unbindData(this.data); if ( nu && ! this.bound_ ) this.bindData(this.data); this.args = nu; this.model = this.innerView || nu.view; }},{"name": "data","postSet": function (old, nu) { if ( old && this.bound_ ) this.unbindData(old); if ( nu ) this.bindData(nu); }},{"name": "childData"},{"name": "innerView","postSet": function (old,nu) { this.model = nu; },"help": "Override for prop.view"},{"name": "view","type": "foam.ui.View","adapt": function (_, v) { return v && v.toView_ ? v.toView_() : v; }},{model_:"BooleanProperty","name": "bound_","defaultValue": false},{"name": "parent","type": "foam.ui.View","postSet": function (_, p) { if ( ! p ) return; // TODO(jacksonic): We shouldn't pretend we aren't part of the tree p[this.prop.name + 'View'] = this.view; if ( this.view ) this.view.parent = p; }}],"methods": [{"name": "unbindData","code": function (oldData) { if ( ! this.bound_ || ! oldData || ! this.prop ) return; var pValue = oldData.propertyValue(this.prop.name); Events.unlink(pValue, this.childData$); this.bound_ = false; }},{"name": "bindData","code": function (data) { if ( this.bound_ || ! data || ! this.prop) return; var pValue = data.propertyValue(this.prop.name); Events.link(pValue, this.childData$); this.bound_ = true; }},{"name": "toString","code": function () { /* Name info. */ return 'PropertyView(' + this.prop.name + ', ' + this.view + ')'; }},{"name": "destroy","code": function ( isParentDestroyed ) { /* Passthrough to $$DOC{ref:'.view'} */ // always unbind, since if our parent was the top level destroy we need // to unhook if we were created as an addSelfDataChild this.unbindData(this.data); this.SUPER( isParentDestroyed ); }},{"name": "construct","code": function () { // if not bound yet and we do have data set, bind it this.bindData(this.data); this.SUPER(); }},{"name": "finishRender","code": function (view) { this.SUPER(view); this.view.prop = this.prop; }},{"name": "addDataChild","code": function (child) { Events.link(this.childData$, child.data$); this.addChild(child); }}]}) CLASS({"package": "foam.ui","name": "AsyncLoadingView","extendsModel": "foam.ui.BaseView","requires": ["Model"],"properties": [{"name": "id","label": "Element ID","type": "String"},{"name": "name","label": "The parent view's name for this"},{"name": "model","label": "View model name, model definition, or JSON with a factory_ specified."},{"name": "args","label": "View construction arguments","defaultValueFn": function () { return {}; }},{"name": "copyFrom","label": "Additional arguments to this.copyFrom(...) when ready.","lazyFactory": function () { return {}; }},{"name": "view","type": "foam.ui.View"}],"methods": [{"name": "init","code": function () { this.SUPER(); this.construct(); }},{"name": "mergeWithCopyFrom","code": function (other) { /* Override/Append to args, typically used to merge in $$DOC{ref:'.model'} if it is a JSON object. */ for (var key in other) { if ( key == 'factory_' ) continue; this.copyFrom[key] = other[key]; } }},{"name": "construct","code": function () { /* Picks the model to create, then passes off to $$DOC{ref:'.finishRender'}. */ // Decorators to allow us to skip over keys without copying them // as create() args var skipKeysArgDecorator = { __proto__: this.args, __SKD_SKIP_KEYS: { factory_: true, model_: true, view: true }, hasOwnProperty: function(name) { if ( ! this.__SKD_SKIP_KEYS[name] ) { return this.__proto__.hasOwnProperty(name); } return false; } }; // HACK to ensure model-for-model works. It requires that 'model', if specified, // be present in the create({ args }). Since we set Actions and Properties as // the create arg object sometimes, we must temporarily transfer the model // value from copyFrom to args, but since we are wrapping it anyways we can // piggyback our model value on the wrapper. if ( this.copyFrom && this.copyFrom.model ) { skipKeysArgDecorator.model = this.copyFrom.model; } if ( this.copyFrom && this.copyFrom.model_ ) { if ( typeof this.copyFrom.model_ === 'string' ) { // string model_ in copyFrom return this.requireModelName(this.copyFrom.model_, skipKeysArgDecorator); } else if ( this.Model.isInstance(this.copyFrom.model_) ) { // or model instance return this.finishRender(this.copyFrom.model_.create(skipKeysArgDecorator, this.X)); } } if ( typeof this.model === 'string' ) { // string model name return this.requireModelName(this.model, skipKeysArgDecorator); } if ( this.model.model_ && typeof this.model.model_ === 'string' ) { // JSON instance def'n // FOAMalize the definition return this.requireViewInstance(FOAM(this.model)); } if ( this.model.model_ ) { if ( this.Model.isInstance(this.model) ) { // is a model instance return this.finishRender(this.model.create(skipKeysArgDecorator, this.X)); } else { // JSON with Model instance specified in model_ this.mergeWithCopyFrom(this.model); return this.finishRender(this.model.model_.create(skipKeysArgDecorator, this.X)); } } if ( this.model.factory_ ) { // JSON with string factory_ name // TODO: previously 'view' was removed from copyFrom to support CViews not getting their view stomped. Put back... this.mergeWithCopyFrom(this.model); return this.requireModelName(this.model.factory_, skipKeysArgDecorator); } if ( typeof this.model === 'function' ) { // factory function return this.finishRender(this.model(skipKeysArgDecorator, this.X)); } console.warn("AsyncLoadingView: View load with invalid model. ", this.model, this.args, this.copyFrom); }},{"name": "requireViewInstance","code": function (view) { view.arequire(this.X)(function(m) { this.finishRender(view); }.bind(this)); }},{"name": "requireModelName","code": function (name, args) { arequire(name, this.X)(function(m) { this.finishRender(m.create(args, this.X)); }.bind(this)); }},{"name": "finishRender","code": function (view) { if ( this.copyFrom ) { // don't copy a few special cases var skipKeysCopyFromDecorator = { __proto__: this.copyFrom, __SKD_SKIP_KEYS: { factory_: true, model_: true, view: true, }, hasOwnProperty: function(name) { if ( ! this.__SKD_SKIP_KEYS[name] ) { return this.__proto__.hasOwnProperty(name); } return false; } } view.copyFrom(skipKeysCopyFromDecorator); } this.view = view.toView_(); this.addDataChild(this.view); var el = this.X.$(this.id); if ( el ) { el.outerHTML = this.toHTML(); this.initHTML(); } }},{"name": "toHTML","code": function () { /* If the view is ready, pass through to it. Otherwise create a place holder tag with our id, which we replace later. */ return this.view ? this.view.toHTML() : ('<div id="'+this.id+'"></div>'); }},{"name": "initHTML","code": function () { this.view && this.view.initHTML(); }},{"name": "toString","code": function () { /* Name info. */ return 'AsyncLoadingView(' + this.model + ', ' + this.view + ')'; }},{"name": "fromElement","code": function (e) { /* passthru */ this.view.fromElement(e); return this; }}]}) CLASS({"package": "foam.ui","name": "BaseView","extendsModel": "foam.patterns.ChildTreeTrait","properties": [{"name": "data"}],"methods": [{"name": "addDataChild","code": function (child) { /* For children that link to data$. Override to track the connections, if required. */ Events.link(this.data$, child.data$); this.addChild(child); }},{"name": "addSelfDataChild","code": function (child) { /* For views created from properties of this view (not our data), this method sets the child's data to 'this'. */ child.data = this; this.addChild(child); }},{"name": "toView_","code": function () { /* if you are a BaseView that can be converted into an html View, convert here */ return this; }}]}) CLASS({"package": "foam.patterns","name": "ChildTreeTrait","properties": [{"name": "parent","type": "foam.patterns.ChildTreeTrait","hidden": true},{"name": "children","type": "Array[foam.patterns.ChildTreeTrait]","factory": function () { return []; }}],"methods": [{"name": "onAncestryChange_","code": function () { /* Called when our parent or an ancestor's parent changes. Override to react to ancestry changes. Remember to call <code>this.SUPER()</code>. */ Array.prototype.forEach.call(this.children, function(c) { c.onAncestryChange_ && c.onAncestryChange_() } ); }},{"name": "addChild","code": function (child) { /* Maintains the tree structure of $$DOC{ref:'foam.ui.View',usePlural:true}. When a sub-$$DOC{ref:'foam.ui.View'} is created, add it to the tree with this method. */ //if (arguments.callee.caller.super_) this.SUPER(child); // Check prevents duplicate addChild() calls, // which can happen when you use creatView() to create a sub-view (and it calls addChild) // and then you write the View using TemplateOutput (which also calls addChild). // That should all be cleaned up and all outputHTML() methods should use TemplateOutput. if ( child.parent === this ) return; child.parent = this; child.onAncestryChange_ && child.onAncestryChange_(); var children = this.children; children.push(child); this.children = children; return this; }},{"name": "removeChild","code": function (child) { /* Maintains the tree structure of $$DOC{ref:'foam.ui.View',usePlural:true}. When a sub-$$DOC{ref:'foam.ui.View'} is destroyed, remove it from the tree with this method. The isParentDestroyed argument is passed to the child's destroy(). */ child.destroy && child.destroy(true); this.children.deleteI(child); child.parent = undefined; //child.onAncestryChange_(); return this; }},{"name": "removeAllChildren","code": function (isParentDestroyed) { // unhook the children list, then destroy them all var list = this.children; this.children = []; Array.prototype.forEach.call(list, function(child) { this.removeChild(child); }.bind(this)); }},{"name": "addChildren","code": function () { /* Adds multiple children at once. Specify each child to add as an argument. */ for ( var i = 0; i < arguments.length; ++i ) { this.addChild(arguments[i]); } return this; }},{"name": "destroy","code": function ( isParentDestroyed ) { /* Destroys children and removes them from this. Override to include your own cleanup code, but always call this.SUPER(isParentDestroyed) after you are done. When isParentDestroyed is true, your parent has already been destroyed. You may choose to omit unecessary cleanup. */ if ( isParentDestroyed ) { // console.log(this.name_, " FAST destroying ", this.children.length," children"); Array.prototype.forEach.call(this.children, function(child) { child.destroy && child.destroy(true); }); } else { // console.log(this.name_, " SLOW removing ", this.children.length," children--------------------------------------"); this.removeAllChildren(); } return this; }},{"name": "construct","code": function () { /* After a destroy(), construct() is called to fill in the object again. If any special children need to be re-created, do it here. */ return this; }},{"name": "deepPublish","code": function (topic) { /* Publish an event and cause all children to publish as well. */ var count = this.publish.apply(this, arguments); if ( this.children ) { for ( var i = 0 ; i < this.children.length ; i++ ) { var child = this.children[i]; count += child.deepPublish.apply(child, arguments); } } return count; }}]}) CLASS({"package": "foam.core.types","name": "DocumentInstallProperty","extendsModel": "Property","properties": [{model_:"FunctionProperty","name": "documentInstallFn"}],"methods": [{"name": "initPropertyAgents","code": function (proto, fastInit) { this.SUPER(proto, fastInit); var thisProp = this; var DocumentInstallProperty = thisProp.model_; // add the agent for this model proto.addInitAgent(12, ': install in document ', function(o, X, Y) { // o is a a newly created instance of a model that has a DocumentInstallProperty var model = o.model_; // if not a model instance, no document, or we are already installed // in document, we're done. if ( ! model || ! X.installedModels || X.installedModels[model.id] ) return; // call this document installer function on the current proto thisProp.documentInstallFn.call(proto, X); }); // Also run our base models' DocumentInstallProperty inits, in case no // instances of our base models have been created. if ( proto.__proto__.model_ ) { var recurse = function(baseProto) { // if the base model also has/inherits this property, init on base too var baseProp = baseProto.model_.getProperty(thisProp.name); if ( baseProp ) { // add a special init agent that has the proto hardcoded. proto.addInitAgent(12, ': inherited install in document ', function(o, X, Y) { var model = baseProto.model_; if ( ! model || ! X.installedModels || X.installedModels[model.id] ) return; baseProp.documentInstallFn.call(baseProto, X); }); // many of these may be added, but won't hurt proto.addInitAgent(13, ': completed inherited install in document ', function(o, X, Y) { X.installedModels[baseProto.model_.id] = true; }); // continue recursing if ( baseProto.__proto__.model_ ) { recurse(baseProto.__proto__); } } // else this property is not declared or inherited at this level, so we are done. } recurse(proto.__proto__); } // run after all the install in document agents to mark completion proto.addInitAgent(13, ': completed install in document ', function(o, X, Y) { X.installedModels[o.model_.id] = true; }); }}],"help": "Describes a function property that runs once per document"}) CLASS({"package": "foam.core.types","name": "StringEnumProperty","extendsModel": "StringProperty","traits": ["foam.core.types.EnumPropertyTrait"]}) CLASS({"package": "foam.core.types","name": "EnumPropertyTrait","properties": [{"name": "choices","type": "Array","required": true,"preSet": function (_, a) { return a.map(function(c) { return Array.isArray(c) ? c : [c, c]; }); },"help": "Array of [value, label] choices."},{"name": "view","defaultValue": "foam.ui.ChoiceView"}]}) CLASS({"package": "foam.ui","name": "DAOListView","extendsModel": "foam.ui.View","traits": ["foam.ui.DAODataViewTrait"],"requires": ["SimpleValue"],"properties": [{model_:"BooleanProperty","name": "isHidden","postSet": function (_, isHidden) { if ( this.dao && ! isHidden ) this.onDAOUpdate(); },"defaultValue": false},{model_:"ViewFactoryProperty","name": "rowView","defaultValue": "foam.ui.DetailView"},{"name": "mode","view": {"factory_": "foam.ui.ChoiceView","choices": ["read-only","read-write","final"]},"defaultValue": "read-write"},{"name": "useSelection","postSet": function (old, nu) { if ( this.useSelection && !this.X.selection$ ) this.X.selection$ = this.SimpleValue.create(); this.selection$ = this.X.selection$; },"help": "Backward compatibility for selection mode. Create a X.selection$ value in your context instead."},{"name": "selection","factory": function () { return this.SimpleValue.create(); },"help": "Backward compatibility for selection mode. Create a X.selection$ value in your context instead."},{"name": "scrollContainer","help": "Containing element that is responsible for scrolling."},{"name": "chunkSize","defaultValue": 0,"help": "Number of entries to load in each infinite scroll chunk."},{"name": "chunksLoaded","defaultValue": 1,"help": "The number of chunks currently loaded."},{model_:"BooleanProperty","name": "painting","transient": true,"defaultValue": false},{model_:"BooleanProperty","name": "repaintRequired","transient": true,"defaultValue": false}],"constants": [{"name": "ROW_CLICK","value": ["row-click"]}],"methods": [{"name": "init","code": function () { this.SUPER(); var self = this; this.subscribe(this.ON_HIDE, function() { self.isHidden = true; }); this.subscribe(this.ON_SHOW, function() { self.isHidden = false; }); // bind to selection, if present if (this.X.selection$) { this.selection$ = this.X.selection$; } }},{"name": "initHTML","code": function () { this.SUPER(); // If we're doing infinite scrolling, we need to find the container. // Either an overflow: scroll element or the window. // We keep following the parentElement chain until we get null. if ( this.chunkSize > 0 ) { var e = this.$; while ( e ) { if ( window.getComputedStyle(e).overflow === 'scroll' ) break; e = e.parentElement; } this.scrollContainer = e || window; this.scrollContainer.addEventListener('scroll', this.onScroll, false); } if ( ! this.isHidden ) this.updateHTML(); }},{"name": "construct","code": function () { if ( ! this.dao || ! this.$ ) return; if ( this.painting ) { this.repaintRequired = true; return; } this.painting = true; var out = []; this.children = []; this.initializers_ = []; var doneFirstItem = false; var d = this.dao; if ( this.chunkSize ) { d = d.limit(this.chunkSize * this.chunksLoaded); } d.select({put: function(o) { if ( this.mode === 'read-write' ) o = o.model_.create(o, this.Y); //.clone(); var view = this.rowView({data: o, model: o.model_}, this.Y); // TODO: Something isn't working with the Context, fix view.DAO = this.dao; if ( this.mode === 'read-write' ) { o.addPropertyListener(null, function(o, topic) { var prop = o.model_.getProperty(topic[1]); // TODO(kgr): remove the deepClone when the DAO does this itself. if ( ! prop.transient ) view.DAO.put(o.deepClone()); }); } this.addChild(view); if ( ! doneFirstItem ) { doneFirstItem = true; } else { this.separatorToHTML(out); // optional separator } if ( this.X.selection$ ) { out.push('<div class="' + this.className + '-row' + '" id="' + this.on('click', (function() { this.selection = o; this.publish(this.ROW_CLICK); }).bind(this)) + '">'); } out.push(view.toHTML()); if ( this.X.selection$ ) { out.push('</div>'); } }.bind(this)})(function() { if (this.repaintRequired) { this.repaintRequired = false; this.painting = false; this.realDAOUpdate(); return; } var e = this.$; if ( ! e ) return; e.innerHTML = out.join(''); this.initInnerHTML(); this.painting = false; }.bind(this)); }},{"name": "fromElement","code": function (e) { var children = e.children; if ( children.length == 1 && children[0].nodeName === 'rowView' ) { this.SUPER(e); } else { this.rowView = e.innerHTML; } }},{"name": "separatorToHTML","code": function (out) { /* Template method. Override to provide a separator if required. This method is called <em>before</em> each list item, except the first. Use out.push("<myhtml>...") for efficiency. */ }}],"listeners": [{"name": "onDAOUpdate","code": function () { this.realDAOUpdate(); }},{"name": "realDAOUpdate","code": function () { if ( ! this.isHidden ) this.updateHTML(); },"isFramed": true},{"name": "onScroll","code": function () { var e = this.scrollContainer; if ( this.chunkSize > 0 && e.scrollTop + e.offsetHeight >= e.scrollHeight ) { this.chunksLoaded++; this.updateHTML(); } }}]}) CLASS({"package": "foam.ui","name": "DAODataViewTrait","exports": ["dao$ as daoViewCurrentDAO$"],"properties": [{"name": "data","preSet": function (old, nu) { if ( this.dao !== nu ) { this.dao = nu; } return nu; }},{model_:"foam.core.types.DAOProperty","name": "dao","label": "DAO","postSet": function (oldDAO, dao) { if ( ! dao ) { this.data = ''; } else if ( ! equals(this.data, dao) ) { this.data = dao; } },"help": "An alias for the data property.","onDAOUpdate": "onDAOUpdate"}],"methods": [{"name": "onDAOUpdate","code": function () { /* Implement this $$DOC{ref:'Method'} in sub-models to respond to changes in $$DOC{ref:'.dao'}. */ }}]}) CLASS({"package": "foam.core.types","name": "DAOProperty","extendsModel": "Property","requires": ["foam.dao.FutureDAO","foam.dao.ProxyDAO"],"imports": ["console"],"properties": [{"name": "type","defaultValue": "DAO","help": "The FOAM type of this property."},{model_:"ModelProperty","name": "model","help": "The model for objects stored in the DAO."},{"name": "view","defaultValue": "foam.ui.DAOListView"},{"name": "onDAOUpdate"},{"name": "install","defaultValue": function (prop) { defineLazyProperty(this, prop.name + '$Proxy', function() { if ( ! this[prop.name] ) { var future = afuture(); var delegate = prop.FutureDAO.create({ future: future.get }); } else delegate = this[prop.name]; var proxy = prop.ProxyDAO.create({delegate: delegate}); this.addPropertyListener(prop.name, function(_, _, _, dao) { if ( future ) { future.set(dao); future = null; return; } proxy.delegate = dao; }); return { get: function() { return proxy; }, configurable: true }; }); }},{"name": "fromElement_","defaultValue": function (e, p, model) { var children = e.children; for ( var i = 0 ; i < children.length ; i++ ) { this[p.name].put(model.create(null, this.Y).fromElement( children[i], p)); } }},{"name": "fromElement","defaultValue": function (e, p) { var model = e.getAttribute('model') || (this[p.name] && this[p.name].model) || p.model || ''; if ( ! model ) { this.console.warn('Attempt to load DAO from element without model'); return; } if ( typeof model === 'string' ) { arequire(model, this.X)(function(model) { p.fromElement_.call(this, e, p, model); }.bind(this)); } else { p.fromElement_.call(this, e, p, model); } }}],"help": "Describes a DAO property."}) CLASS({"package": "foam.dao","name": "FutureDAO","extendsModel": "foam.dao.ProxyDAO","properties": [{"name": "delegate","factory": function () { return null; },"postSet": function (oldDAO, newDAO) { if ( this.daoListeners_.length ) { if ( oldDAO ) oldDAO.unlisten(this.relay()); newDAO.listen(this.relay()); } }},{"name": "future","required": true},{"name": "model","defaultValueFn": function () { return this.delegate ? this.delegate.model : ''; }}],"methods": [{"name": "init","code": function () { /* Sets up the future to provide us with the delegate when it becomes available. */ this.SUPER(); this.future(function(delegate) { this.delegate = delegate; }.bind(this)); }},{"name": "put","code": function (value, sink) { /* Passthrough to delegate or the future, if delegate not set yet. */ if ( this.delegate ) { this.delegate.put(value, sink); } else { this.future(this.put.bind(this, value, sink)); } }},{"name": "remove","code": function (query, sink) { /* Passthrough to delegate or the future, if delegate not set yet. */ if ( this.delegate ) { this.delegate.remove(query, sink); } else { this.future(this.remove.bind(this, query, sink)); } }},{"name": "removeAll","code": function () { /* Passthrough to delegate or the future, if delegate not set yet. */ if ( this.delegate ) { return this.delegate.removeAll.apply(this.delegate, arguments); } var a = arguments; var f = afuture(); this.future(function(delegate) { this.removeAll.apply(this, a)(f.set); }.bind(this)); return f.get; }},{"name": "find","code": function (key, sink) {/* Passthrough to delegate or the future, if delegate not set yet. */ if ( this.delegate ) { this.delegate.find(key, sink); } else { this.future(this.find.bind(this, key, sink)); } }},{"name": "select","code": function (sink, options) {/* Passthrough to delegate or the future, if delegate not set yet. */ if ( this.delegate ) { return this.delegate.select(sink, options); } var a = arguments; var f = afuture(); this.future(function() { this.select.apply(this, a)(f.set); }.bind(this)); return f.get; }}]}) CLASS({"package": "foam.dao","name": "ProxyDAO","extendsModel": "AbstractDAO","requires": ["foam.dao.NullDAO"],"properties": [{"name": "delegate","type": "DAO","mode": "read-only","required": true,"hidden": true,"transient": true,"factory": function () { return this.NullDAO.create(); },"postSet": function (oldDAO, newDAO) { if ( this.daoListeners_.length ) { if ( oldDAO ) oldDAO.unlisten(this.relay()); newDAO.listen(this.relay()); // FutureDAOs will put via the future. In that case, don't put here. if ( this.X.lookup('foam.dao.FutureDAO') && this.X.lookup('foam.dao.FutureDAO').isInstance(oldDAO) ) { // do nothing } else { this.notify_('reset', []); } } }},{model_:"ModelProperty","name": "model","defaultValueFn": function () { return this.delegate.model; },"type": "Model"}],"methods": [{"name": "relay","code": function () { /* Sets up relay for listening to delegate changes. */ if ( ! this.relay_ ) { var self = this; this.relay_ = { put: function() { self.notify_('put', arguments); }, remove: function() { self.notify_('remove', arguments); }, reset: function() { self.notify_('reset', arguments); }, toString: function() { return 'RELAY(' + this.$UID + ', ' + self.model_.name + ', ' + self.delegate + ')'; } }; } return this.relay_; }},{"name": "put","code": function (value, sink) { /* Passthrough to delegate. */ this.delegate.put(value, sink); }},{"name": "remove","code": function (query, sink) { /* Passthrough to delegate. */ this.delegate.remove(query, sink); }},{"name": "removeAll","code": function () { /* Passthrough to delegate. */ return this.delegate.removeAll.apply(this.delegate, arguments); }},{"name": "find","code": function (key, sink) { /* Passthrough to delegate. */ this.delegate.find(key, sink); }},{"name": "select","code": function (sink, options) { /* Passthrough to delegate. */ return this.delegate.select(sink, options); }},{"name": "listen","code": function (sink, options) { /* Passthrough to delegate, using $$DOC{ref:'.relay'}. */ // Adding first listener, so listen to delegate if ( ! this.daoListeners_.length && this.delegate ) { this.delegate.listen(this.relay()); } this.SUPER(sink, options); }},{"name": "unlisten","code": function (sink) { /* Passthrough to delegate, using $$DOC{ref:'.relay'}. */ this.SUPER(sink); // Remove last listener, so unlisten to delegate if ( this.daoListeners_.length === 0 && this.delegate ) { this.delegate.unlisten(this.relay()); } }},{"name": "toString","code": function () { /* String representation. */ return this.name_ + '(' + this.delegate + ')'; }}]}) CLASS({"package": "foam.dao","name": "NullDAO","methods": [{"name": "put","code": function (obj, sink) { sink && sink.put && sink.put(obj); }},{"name": "remove","code": function (obj, sink) { sink && sink.remove && sink.remove(obj); }},{"name": "select","code": function (sink) { sink && sink.eof && sink.eof(); return aconstant(sink || [].sink); }},{"name": "find","code": function (q, sink) { sink && sink.error && sink.error('find', q); }},{"name": "listen","code": function () {}},{"name": "removeAll","code": function () {}},{"name": "unlisten","code": function () {}},{"name": "pipe","code": function () {}},{"name": "where","code": function () { return this; }},{"name": "limit","code": function () { return this; }},{"name": "skip","code": function () { return this; }}],"help": "A DAO that stores nothing and does nothing."}) CLASS({"package": "foam.ui","name": "View","extendsModel": "foam.ui.DestructiveDataView","traits": ["foam.ui.HTMLViewTrait"],"requires": ["Property"],"exports": ["propertyViewProperty"],"properties": [{"name": "propertyViewProperty","type": "Property","defaultValueFn": function () { return this.Property.DETAIL_VIEW; }}]}) CLASS({"package": "foam.ui","name": "DestructiveDataView","extendsModel": "foam.ui.BaseView","requires": ["SimpleValue"],"properties": [{"name": "data","preSet": function (old,nu) { if ( this.shouldDestroy(old,nu) ) { // destroy children this.destroy(); } return nu; },"postSet": function (old,nu) { if ( this.shouldDestroy(old,nu) ) { // rebuild children with new data (propagation will happen implicitly) this.construct(); } }},{"name": "dataLinkedChildren","type": "Array[foam.patterns.ChildTreeTrait]","factory": function () { return []; }}],"methods": [{"name": "shouldDestroy","code": function (old,nu) { /* Override to provide the destruct condition. When data changes, this method is called. Return true to destroy(), cut loose children and construct(). Return false to retain children and just propagate the data change. */ return true; }},{"name": "destroy","code": function ( isParentDestroyed ) { if ( ! isParentDestroyed ) { // unlink children this.dataLinkedChildren.forEach(function(child) { Events.unfollow(this.data$, child.data$); }.bind(this)); this.dataLinkedChildren = []; }// else { // var parentName = this.parent.name_; // this.data$.addListener(function() { // console.warn("Data changed after fast-destroy! ", this.name_, parentName); // }.bind(this)); // } this.SUPER(isParentDestroyed); }},{"name": "addDataChild","code": function (child) { /* For children that link to data$, this method tracks them for disconnection when we destroy. */ Events.follow(this.data$, child.data$); this.dataLinkedChildren.push(child); this.addChild(child); }}]}) CLASS({"package": "foam.dao","name": "EasyDAO","extendsModel": "foam.dao.ProxyDAO","requires": ["MDAO","foam.core.dao.CloningDAO","foam.core.dao.MigrationDAO","foam.core.dao.StorageDAO","foam.dao.CachingDAO","foam.dao.ContextualizingDAO","foam.dao.DeDupDAO","foam.dao.GUIDDAO","foam.dao.SeqNoDAO"],"properties": [{"name": "name","defaultValueFn": function () { return this.model.plural; }},{model_:"BooleanProperty","name": "seqNo","defaultValue": false},{model_:"BooleanProperty","name": "guid","label": "GUID","defaultValue": false},{"name": "seqProperty","type": "Property"},{model_:"BooleanProperty","name": "cache","defaultValue": false},{model_:"BooleanProperty","name": "dedup","defaultValue": false},{model_:"BooleanProperty","name": "logging","defaultValue": false},{model_:"BooleanProperty","name": "timing","defaultValue": false},{model_:"BooleanProperty","name": "contextualize","defaultValue": false},{model_:"BooleanProperty","name": "cloning","defaultValue": false},{"name": "daoType","defaultValue": "foam.dao.IDBDAO"},{model_:"BooleanProperty","name": "autoIndex","defaultValue": false},{model_:"ArrayProperty","name": "migrationRules","subType": "foam.core.dao.MigrationRule"}],"constants": [{"name": "ALIASES","value": {"IDB": "foam.dao.IDBDAO","LOCAL": "foam.core.dao.StorageDAO","SYNC": "foam.core.dao.StorageDAO"}}],"methods": [{"name": "init","code": function init(args) { /* <p>On initialization, the $$DOC{ref:'.'} creates an appropriate chain of internal $$DOC{ref:'DAO'} instances based on the $$DOC{ref:'.'} property settings.</p> <p>This process is transparent to the developer, and you can use your $$DOC{ref:'.'} like any other $$DOC{ref:'DAO'}.</p> */ this.SUPER(args); if ( window.chrome && chrome.storage ) { this.ALIASES.LOCAL = 'foam.core.dao.ChromeStorageDAO'; this.ALIASES.SYNC = 'foam.core.dao.ChromeSyncStorageDAO'; } var daoType = typeof this.daoType === 'string' ? this.ALIASES[this.daoType] || this.daoType : this.daoType; var daoModel = typeof daoType === 'string' ? this.X.lookup(daoType) : daoType; var params = { model: this.model, autoIndex: this.autoIndex }; if ( this.name ) params.name = this.name; if ( this.seqNo || this.guid ) params.property = this.seqProperty; var dao = daoModel.create(params); if ( MDAO.isInstance(dao) ) { this.mdao = dao; if ( this.dedup ) dao = this.DeDupDAO.create({delegate: dao}); } else { if ( this.migrationRules && this.migrationRules.length ) { dao = this.MigrationDAO.create({ delegate: dao, rules: this.migrationRules, name: this.model.name + "_" + daoModel.name + "_" + this.name }, this.Y); } if ( this.cache ) { this.mdao = this.MDAO.create(params); dao = this.CachingDAO.create({ cache: this.dedup ? this.mdao : this.DeDupDAO.create({delegate: this.mdao}), src: dao, model: this.model}); } } if ( this.seqNo && this.guid ) throw "EasyDAO 'seqNo' and 'guid' features are mutually exclusive."; if ( this.seqNo ) { var args = {__proto__: params, delegate: dao, model: this.model}; if ( this.seqProperty ) args.property = this.seqProperty; dao = this.SeqNoDAO.create(args); } if ( this.guid ) { var args = {__proto__: params, delegate: dao, model: this.model}; if ( this.seqProperty ) args.property = this.seqProperty; dao = this.GUIDDAO.create(args); } if ( this.contextualize ) dao = this.ContextualizingDAO.create({ delegate: dao }); if ( this.cloning ) dao = this.CloningDAO.create({ delegate: dao }); if ( this.timing ) dao = TimingDAO.create(this.name + 'DAO', dao); if ( this.logging ) dao = LoggingDAO.create(dao); this.delegate = dao; }},{"name": "addIndex","code": function addIndex() { /* <p>Only relevant if $$DOC{ref:'.cache'} is true or if $$DOC{ref:'.daoType'} was set to $$DOC{ref:'MDAO'}, but harmless otherwise.</p> <p>See $$DOC{ref:'MDAO.addIndex', text:'MDAO.addIndex()'}.</p> */ this.mdao && this.mdao.addIndex.apply(this.mdao, arguments); return this; }},{"name": "addRawIndex","code": function addRawIndex() { /* <p>Only relevant if $$DOC{ref:'.cache'} is true or if $$DOC{ref:'.daoType'} was set to $$DOC{ref:'MDAO'}, but harmless otherwise.</p> <p>See $$DOC{ref:'MDAO.addRawIndex', text:'MDAO.addRawIndex()'}. */ this.mdao && this.mdao.addRawIndex.apply(this.mdao, arguments); return this; }}],"help": "A facade for easy DAO setup."}) CLASS({"package": "foam.core.dao","name": "CloningDAO","extendsModel": "foam.dao.ProxyDAO","properties": [{model_:"BooleanProperty","name": "onSelect","defaultValue": false}],"methods": [{"name": "select","code": function (sink, options) { if ( ! this.onSelect ) return this.SUPER(sink, options); sink = sink || [].sink; var future = afuture(); this.delegate.select({ put: function(obj, s, fc) { obj = obj.deepClone(); sink.put && sink.put(obj, s, fc); }, error: function() { sink.error && sink.error.apply(sink, argumentS); }, eof: function() { sink.eof && sink.eof(); future.set(sink); } }, options); return future.get; }},{"name": "find","code": function (key, sink) { return this.SUPER(key, { put: function(o) { var clone = o.deepClone(); sink && sink.put && sink.put(clone); }, error: sink && sink.error && sink.error.bind(sink) }); }}]}) CLASS({"package": "foam.core.dao","name": "MigrationDAO","extendsModel": "foam.dao.ProxyDAO","requires": ["foam.core.dao.MigrationRule","foam.dao.FutureDAO","foam.dao.DAOVersion"],"imports": ["daoVersionDao"],"properties": [{"name": "delegate"},{model_:"ArrayProperty","name": "rules","subType": "foam.core.dao.MigrationRule"},{"name": "name"}],"methods": [{"name": "init","code": function () { var dao = this.delegate; var future = afuture() this.delegate = this.FutureDAO.create({future: future.get}); var self = this; var version; aseq( function(ret) { self.daoVersionDao.find(self.name, { put: function(c) { version = c; ret(); }, error: function() { version = self.DAOVersion.create({ name: self.name, version: 0 }); ret(); } }); }, function(ret) { function updateVersion(ret, v) { var c = version.clone(); c.version = v; self.daoVersionDao.put(c, ret); } var rulesDAO = self.rules.dao; rulesDAO .where(AND(GT(self.MigrationRule.VERSION, version.version))) .select()(function(rules) { var seq = []; for ( var i = 0; i < rules.length; i++ ) { (function(rule) { seq.push( aseq( function(ret) { rule.migration(ret, dao); }, function(ret) { updateVersion(ret, rule.version); })); })(self.rules[i]); } if ( seq.length > 0 ) aseq.apply(null, seq)(ret); else ret(); }); })(function() { future.set(dao); }); this.SUPER(); }}]}) CLASS({"package": "foam.core.dao","name": "MigrationRule","ids": ["modelName"],"properties": [{model_:"StringProperty","name": "modelName"},{model_:"IntProperty","name": "version"},{model_:"FunctionProperty","name": "migration"}]}) CLASS({"package": "foam.dao","name": "DAOVersion","ids": ["name"],"properties": [{"name": "name"},{"name": "version"}]}) CLASS({"package": "foam.core.dao","name": "StorageDAO","extendsModel": "MDAO","properties": [{"name": "name","label": "Store Name","type": "String","defaultValueFn": function () { return this.model.plural; }}],"methods": [{"name": "init","code": function () { this.SUPER(); var objs = localStorage.getItem(this.name); if ( objs ) JSONUtil.parse(this.Y, objs).select(this); this.addRawIndex({ execute: function() {}, bulkLoad: function() {}, toString: function() { return "StorageDAO Update"; }, plan: function() { return { cost: Number.MAX_VALUE }; }, put: this.updated, remove: this.updated }); }}],"listeners": [{"name": "updated","code": function () { this.select()(function(a) { localStorage.setItem(this.name, JSONUtil.compact.where(NOT_TRANSIENT).stringify(a)); }.bind(this)); },"isMerged": 100}]}) CLASS({"package": "foam.dao","name": "CachingDAO","extendsModel": "foam.dao.ProxyDAO","requires": ["foam.dao.FutureDAO"],"properties": [{"name": "src"},{"name": "cache","getter": function () { return this.delegate },"setter": function (dao) { this.delegate = dao; },"help": "Alias for delegate."},{"name": "model","defaultValueFn": function () { return this.src.model || this.cache.model; }}],"methods": [{"name": "init","code": function () { this.SUPER(); var src = this.src; var cache = this.cache; var futureDelegate = afuture(); this.cache = this.FutureDAO.create({future: futureDelegate.get}); src.select(cache)(function() { // Actually means that cache listens to changes in the src. src.listen(cache); futureDelegate.set(cache); this.cache = cache; }.bind(this)); }},{"name": "put","code": function (obj, sink) { this.src.put(obj, sink); }},{"name": "remove","code": function (query, sink) { this.src.remove(query, sink); }},{"name": "removeAll","code": function (sink, options) { return this.src.removeAll(sink, options); }}]}) CLASS({"package": "foam.dao","name": "ContextualizingDAO","extendsModel": "foam.dao.ProxyDAO","methods": [{"name": "find","code": function (id, sink) { var X = this.Y; this.delegate.find(id, { put: function(o) { o.X = X; sink && sink.put && sink.put(o); }, error: function() { sink && sink.error && sink.error.apply(sink, arguments); } }); }}]}) CLASS({"package": "foam.dao","name": "DeDupDAO","extendsModel": "foam.dao.ProxyDAO","methods": [{"name": "put","code": function put(obj, sink) { this.dedup(obj); this.delegate.put(obj, sink); }},{"name": "dedup","code": function dedup(obj) { var inst = obj.instance_; for ( var key in inst ) { var val = inst[key]; if ( typeof val === 'string' ) { inst[key] = val.intern(); } } }}]}) CLASS({"package": "foam.dao","name": "GUIDDAO","label": "foam.dao.GUIDDAO","extendsModel": "foam.dao.ProxyDAO","properties": [{"name": "property","type": "Property","required": true,"hidden": true,"transient": true,"defaultValueFn": function () { return this.delegate.model ? this.delegate.model.ID : undefined; }}],"methods": [{"name": "put","code": function (obj, sink) { if ( ! obj.hasOwnProperty(this.property.name) ) obj[this.property.name] = createGUID(); this.delegate.put(obj, sink); }}]}) CLASS({"package": "foam.dao","name": "SeqNoDAO","label": "foam.dao.SeqNoDAO","extendsModel": "foam.dao.ProxyDAO","properties": [{"name": "property","type": "Property","required": true,"hidden": true,"transient": true,"defaultValueFn": function () { return this.delegate.model ? this.delegate.model.ID : undefined; }},{model_:"IntProperty","name": "sequenceValue","defaultValue": 1}],"methods": [{"name": "init","code": function () { this.SUPER(); var future = afuture(); this.WHEN_READY = future.get; // Scan all DAO values to find the largest this.delegate.select(MAX(this.property))(function(max) { if ( max.max ) this.sequenceValue = max.max + 1; future.set(true); }.bind(this)); }},{"name": "put","code": function (obj, sink) { this.WHEN_READY(function() { var val = this.property.f(obj); if ( ! val || val == this.property.defaultValue ) { obj[this.property.name] = this.sequenceValue++; } this.delegate.put(obj, sink); }.bind(this)); }}]}) CLASS({"package": "foam.memento","name": "WindowHashValue","imports": ["window"],"methods": [{"name": "get","code": function () { return this.window.location.hash ? this.window.location.hash.substring(1) : ''; }},{"name": "set","code": function (value) { this.window.location.hash = value; }},{"name": "addListener","code": function (listener) { this.window.addEventListener('hashchange', listener, false); }},{"name": "removeListener","code": function (listener) { this.window.removeEventListener('hashchange', listener, false); }},{"name": "toString","code": function () { return "WindowHashValue(" + this.get() + ")"; }}]}) CLASS({"package": "com.todomvc","name": "Todo","properties": [{"name": "id"},{model_:"BooleanProperty","name": "completed"},{"name": "text","preSet": function (_, text) { return text.trim(); }}],"templates": [{"name": "toDetailHTML","template": "\u000a\u0009\u0009\u0009\u0009<li id=\"%%id\">\u000a\u0009\u0009\u0009\u0009\u0009<div class=\"view\">\u000a\u0009\u0009\u0009\u0009\u0009\u0009$$completed{className: 'toggle'}\u000a\u0009\u0009\u0009\u0009\u0009\u0009$$text{mode: 'read-only', tagName: 'label'}\u000a\u0009\u0009\u0009\u0009\u0009\u0009<button class=\"destroy\" id=\"<%= this.on('click', function () { this.parent.dao.remove(this.data); }) %>\"></button>\u000a\u0009\u0009\u0009\u0009\u0009</div>\u000a\u0009\u0009\u0009\u0009\u0009$$text{className: 'edit'}\u000a\u0009\u0009\u0009\u0009</li>\u000a\u0009\u0009\u0009\u0009<%\u000a\u0009\u0009\u0009\u0009\u0009var toEdit = function () { DOM.setClass(this.$, 'editing'); this.textView.focus(); }.bind(this);\u000a\u0009\u0009\u0009\u0009\u0009var toDisplay = function () { DOM.setClass(this.$, 'editing', false); }.bind(this);\u000a\u0009\u0009\u0009\u0009\u0009this.on('dblclick', toEdit, this.id);\u000a\u0009\u0009\u0009\u0009\u0009this.on('blur', toDisplay, this.textView.id);\u000a\u0009\u0009\u0009\u0009\u0009this.textView.subscribe(this.textView.ESCAPE, toDisplay);\u000a\u0009\u0009\u0009\u0009\u0009this.setClass('completed', function () { return this.data.completed; }.bind(this), this.id);\u000a\u0009\u0009\u0009\u0009%>\u000a\u0009\u0009\u0009"}]}) CLASS({"package": "com.todomvc","name": "TodoDAO","extendsModel": "foam.dao.ProxyDAO","methods": [{"name": "put","code": function put(issue, s) { // If the user tried to put an empty text, remove the entry instead. if (!issue.text) { this.remove(issue.id, { remove: s && s.put }); } else { this.SUPER(issue, s); } }}]}) CLASS({"package": "com.todomvc","name": "TodoFilterView","extendsModel": "foam.ui.ChoiceListView","requires": ["com.todomvc.Todo"],"properties": [{"name": "choices","factory": function () { return [[TRUE, 'All'], [NOT(this.Todo.COMPLETED), 'Active'], [this.Todo.COMPLETED, 'Completed']]; }}],"methods": [{"name": "choiceToHTML","code": function choiceToHTML(id, choice) { var self = this; this.setClass('selected', function () { return self.text === choice[1]; }, id); return '<li><a id="' + id + '" class="choice">' + choice[1] + '</a></li>'; }}]}) CLASS({"package": "foam.ui","name": "ChoiceListView","extendsModel": "foam.ui.AbstractChoiceView","properties": [{"name": "orientation","view": {"factory_": "foam.ui.ChoiceView","choices": [["horizontal","Horizontal"],["vertical","Vertical"]]},"defaultValue": "horizontal","postSet": function (old, nu) { if ( this.$ ) { DOM.setClass(this.$, old, false); DOM.setClass(this.$, nu); } }},{"name": "className","defaultValueFn": function () { return 'foamChoiceListView ' + this.orientation; }},{"name": "tagName","defaultValue": "ul"},{"name": "innerTagName","defaultValue": "li"}],"methods": [{"name": "init","code": function () { this.SUPER(); // Doing this at the low level rather than with this.setClass listeners // to avoid creating loads of listeners when autocompleting or otherwise // rapidly changing this.choices. this.index$.addListener(this.updateSelected); this.choices$.addListener(this.updateSelected); }},{"name": "choiceToHTML","code": function (id, choice) { return '<' + this.innerTagName + ' id="' + id + '" class="choice">' + choice[1] + '</' + this.innerTagName + '>'; }},{"name": "toInnerHTML","code": function () { var out = []; for ( var i = 0 ; i < this.choices.length ; i++ ) { var choice = this.choices[i]; var id = this.nextID(); this.on( 'click', function(index) { this.choice = this.choices[index]; }.bind(this, i), id); out.push(this.choiceToHTML(id, choice)); } return out.join(''); }},{"name": "initInnerHTML","code": function () { this.SUPER(); this.updateSelected(); }},{"name": "scrollToSelection","code": function () { // Three cases: in view, need to scroll up, need to scroll down. // First we determine the parent's scrolling bounds. var e = this.$.children[this.index]; if ( ! e ) return; var parent = e.parentElement; while ( parent ) { var overflow = this.X.window.getComputedStyle(parent).overflow; if ( overflow === 'scroll' || overflow === 'auto' ) { break; } parent = parent.parentElement; } parent = parent || this.X.window; if ( e.offsetTop < parent.scrollTop ) { // Scroll up e.scrollIntoView(true); } else if ( e.offsetTop + e.offsetHeight >= parent.scrollTop + parent.offsetHeight ) { // Down e.scrollIntoView(); } }}],"listeners": [{"name": "updateSelected","code": function () { if ( ! this.$ || ! this.$.children ) return; for ( var i = 0 ; i < this.$.children.length ; i++ ) { var c = this.$.children[i]; DOM.setClass(c, 'selected', i === this.index); } }}],"templates": [{"name": "CSS","template": "\u000a.foamChoiceListView {\u000a list-style-type: none;\u000a}\u000a\u000a.foamChoiceListView .selected {\u000a font-weight: bold;\u000a}\u000a\u000a.foamChoiceListView.vertical {\u000a padding: 0;\u000a}\u000a.foamChoiceListView.vertical .choice {\u000a margin: 4px;\u000a}\u000a\u000a.foamChoiceListView.horizontal {\u000a padding: 0;\u000a}\u000a.foamChoiceListView.horizontal .choice {\u000a display: inline;\u000a margin: 12px;\u000a}"}]}) CLASS({"package": "foam.ui","name": "AbstractChoiceView","extendsModel": "foam.ui.View","properties": [{model_:"BooleanProperty","name": "autoSetData","help": "If true, this.data is set when choices update and the current data is not one of the choices.","defaultValue": true},{"name": "prop","hidden": true},{"name": "label","help": "The user-visible label for the ChoiceView. Not to be confused with $$DOC{ref:\".text\"}, the name of the currently selected choice."},{"name": "text","postSet": function (_, d) { for ( var i = 0 ; i < this.choices.length ; i++ ) { if ( this.choices[i][1] === d ) { if ( this.index !== i ) this.index = i; return; } } },"help": "The user-visible text of the current choice (ie. [value, text] -> text)."},{"name": "choice","getter": function () { var value = this.data; for ( var i = 0 ; i < this.choices.length ; i++ ) { var choice = this.choices[i]; if ( value === choice[0] ) return choice; } return undefined; },"setter": function (choice) { var oldValue = this.choice; this.data = choice[0]; this.text = choice[1]; this.propertyChange('choice', oldValue, this.choice); },"help": "The current choice (ie. [value, text])."},{"name": "choices","type": "Array[StringField]","preSet": function (_, a) { // If a is a map, instead of an array, we make [key, value] pairs. if ( typeof a === 'object' && ! Array.isArray(a) ) { var out = []; for ( var key in a ) { if ( a.hasOwnProperty(key) ) out.push([key, a[key]]); } return out; } a = a.clone(); // Upgrade single values to [value, value] for ( var i = 0 ; i < a.length ; i++ ) if ( ! Array.isArray(a[i]) ) a[i] = [a[i], a[i]]; return a; },"postSet": function (oldValue, newValue) { var value = this.data; // Update current choice when choices update. for ( var i = 0 ; i < newValue.length ; i++ ) { var choice = newValue[i]; if ( value === choice[0] ) { if ( this.useSelection ) this.index = i; else this.choice = choice; break; } } if ( this.autoSetData && i === newValue.length ) { if ( this.useSelection ) this.index = 0; else this.data = newValue.length ? newValue[0][0] : undefined; } // check if the display labels changed var labelsChanged = true; if ( (oldValue && oldValue.length) == (newValue && newValue.length) ) { labelsChanged = false; for (var i = 0; i < oldValue.length; ++i) { if ( ! equals(oldValue[i][1], newValue[i][1]) ) { labelsChanged = true; break; } } } if ( labelsChanged ) { this.updateHTML(); } }},{model_:"IntProperty","name": "index","transient": true,"preSet": function (_, i) { if ( i < 0 || this.choices.length == 0 ) return 0; if ( i >= this.choices.length ) return this.choices.length - 1; return i; },"postSet": function (_, i) { // If useSelection is enabled, don't update data or choice. if ( this.useSelection ) return; if ( this.choices.length && this.data !== this.choices[i][0] ) this.data = this.choices[i][0]; },"help": "The index of the current choice.","defaultValue": -1},{model_:"FunctionProperty","name": "objToChoice","help": "A Function which adapts an object from the DAO to a [key, value, ...] choice."},{model_:"BooleanProperty","name": "useSelection","help": "When set, data and choice do not update until an entry is firmly selected"},{model_:"foam.core.types.DAOProperty","name": "dao","onDAOUpdate": "onDAOUpdate"},{"name": "data","postSet": function (old, nu) { for ( var i = 0 ; i < this.choices.length ; i++ ) { if ( this.choices[i][0] === nu ) { if ( this.index !== i ) { this.text = this.choices[i][1]; this.index = i; } return; } } if ( nu && this.choices.length ) console.warn('ChoiceView data set to invalid choice: ', nu); }}],"methods": [{"name": "initHTML","code": function () { this.SUPER(); this.dao = this.dao; }},{"name": "findChoiceIC","code": function (name) { name = name.toLowerCase(); for ( var i = 0 ; i < this.choices.length ; i++ ) { if ( this.choices[i][1].toLowerCase() == name ) return this.choices[i]; } }},{"name": "commit","code": function () { if ( this.useSelection && this.choices[this.index] ) this.choice = this.choices[this.index]; }}],"listeners": [{"name": "onDAOUpdate","code": function () { this.dao.select(MAP(this.objToChoice))(function(map) { // console.log('***** Update Choices ', map.arg2, this.choices); this.choices = map.arg2; }.bind(this)); },"isMerged": 100}]}) CLASS({"package": "foam.ui","name": "CSSLoaderTrait","properties": [{model_:"foam.core.types.DocumentInstallProperty","name": "installCSS","documentInstallFn": function (X) { for ( var i = 0 ; i < this.model_.templates.length ; i++ ) { var t = this.model_.templates[i]; if ( t.name === 'CSS' ) { t.futureTemplate(function() { X.addStyle(this.CSS()); }.bind(this)); return; } } }}]}) CLASS({"package": "foam.ui","name": "BooleanView","extendsModel": "foam.ui.SimpleView","properties": [{"name": "data"},{"name": "name","label": "Name","type": "String","defaultValue": "field"}],"methods": [{"name": "toHTML","code": function () { return '<input type="checkbox" id="' + this.id + '" ' + ( this.data ? 'checked ' : '' ) + 'name="' + this.name + '"' + this.cssClassAttr() + '/>'; }},{"name": "initHTML","code": function () { this.domValue = DomValue.create(this.$, 'change', 'checked'); this.$.addEventListener('click', this.onClick); Events.link(this.data$, this.domValue); }},{"name": "destroy","code": function (isParentDestroyed) { this.SUPER(isParentDestroyed); Events.unlink(this.domValue, this.data$); }}],"listeners": [{"name": "onClick","code": function (e) { e.stopPropagation(); }}]}) CLASS({"package": "foam.ui","name": "DetailView","extendsModel": "foam.ui.View","requires": ["Property","foam.ui.TextFieldView","foam.ui.IntFieldView","foam.ui.FloatFieldView","foam.ui.DAOController"],"exports": ["propertyViewProperty"],"properties": [{"name": "className","defaultValue": "detailView"},{"name": "data","preSet": function (old,nu) { if ( nu.model_ ) { this.model = nu.model_; } return nu; }},{"name": "model","type": "Model"},{"name": "title","defaultValueFn": function () { return "Edit " + this.model.label; }},{model_:"StringProperty","name": "mode","defaultValue": "read-write"},{model_:"BooleanProperty","name": "showRelationships","defaultValue": false},{"name": "propertyViewProperty","type": "Property","defaultValueFn": function () { return this.Property.DETAIL_VIEW; }}],"methods": [{"name": "shouldDestroy","code": function (old,nu) { if ( ! old || ! old.model_ || ! nu || ! nu.model_ ) return true; return old.model_ !== nu.model_; }},{"name": "generateContent","code": function () { /* rebuilds the children of the view */ if ( ! this.$ ) return; this.$.outerHTML = this.toHTML(); this.initHTML(); }},{"name": "titleHTML","code": function () { /* Title text HTML formatter */ var title = this.title; return title ? '<tr><th colspan=2 class="heading">' + title + '</th></tr>' : ''; }},{"name": "startForm","code": function () { /* HTML formatter */ return '<table>'; }},{"name": "endForm","code": function () { /* HTML formatter */ return '</table>'; }},{"name": "startColumns","code": function () { /* HTML formatter */ return '<tr><td colspan=2><table valign=top><tr><td valign=top><table>'; }},{"name": "nextColumn","code": function () { /* HTML formatter */ return '</table></td><td valign=top><table valign=top>'; }},{"name": "endColumns","code": function () { /* HTML formatter */ return '</table></td></tr></table></td></tr>'; }},{"name": "rowToHTML","code": function (prop, view) { /* HTML formatter for each $$DOC{ref:'Property'} row. */ var str = ""; if ( prop.detailViewPreRow ) str += prop.detailViewPreRow(this); str += '<tr class="detail-' + prop.name + '">'; if ( this.DAOController.isInstance(view) ) { str += "<td colspan=2><div class=detailArrayLabel>" + prop.label + "</div>"; str += view.toHTML(); str += '</td>'; } else { str += "<td class='label'>" + prop.label + "</td>"; str += '<td>'; str += view.toHTML(); str += '</td>'; } str += '</tr>'; if ( prop.detailViewPostRow ) str += prop.detailViewPostRow(this); return str; }},{"name": "toHTML","code": function () { /* Overridden to create the complete HTML content for the $$DOC{ref:'foam.ui.View'}.</p> <p>$$DOC{ref:'Model',usePlural:true} may specify a .toDetailHTML() $$DOC{ref:'Method'} or $$DOC{ref:'Template'} to render their contents instead of the $$DOC{ref:'foam.ui.DetailView.defaultToHTML'} we supply here. */ if ( ! this.data ) return '<span id="' + this.id + '"></span>'; if ( ! this.model ) throw "DetailView: either 'data' or 'model' must be specified."; return (this.model.getPrototype().toDetailHTML || this.defaultToHTML).call(this); }},{"name": "defaultToHTML","code": function () { /* For $$DOC{ref:'Model',usePlural:true} that don't supply a .toDetailHTML() $$DOC{ref:'Method'} or $$DOC{ref:'Template'}, a default listing of $$DOC{ref:'Property'} editors is implemented here. */ this.children = []; var model = this.model; var str = ""; str += '<div id="' + this.id + '" ' + this.cssClassAttr() + '" name="form">'; str += this.startForm(); str += this.titleHTML(); var properties = model.getRuntimeProperties(); for ( var i = 0 ; i < properties.length ; i++ ) { var prop = properties[i]; if ( prop.hidden ) continue; var view = this.createView(prop); //view.data$ = this.data$; this.addDataChild(view); str += this.rowToHTML(prop, view); } str += this.endForm(); if ( this.showRelationships ) { var view = this.X.lookup('foam.ui.RelationshipsView').create({ data: this.data }); //view.data$ = this.data$; this.addDataChild(view); str += view.toHTML(); } str += '</div>'; return str; }}],"templates": [{"name": "CSS","template": "\u000a .detailView {\u000a border: solid 2px #dddddd;\u000a background: #fafafa;\u000a width: 99%;\u000a }\u000a\u000a .detailView .heading {\u000a float: left;\u000a font-size: 14px;\u000a font-weight: bold;\u000a margin-bottom: 8px;\u000a }\u000a\u000a .detailView .propertyLabel {\u000a font-size: 14px;\u000a display: block;\u000a font-weight: bold;\u000a text-align: right;\u000a float: left;\u000a }\u000a\u000a .detailView input {\u000a font-size: 12px;\u000a padding: 4px 2px;\u000a border: solid 1px #aacfe4;\u000a margin: 2px 0 0px 10px;\u000a }\u000a\u000a .detailView textarea {\u000a float: left;\u000a font-size: 12px;\u000a padding: 4px 2px;\u000a border: solid 1px #aacfe4;\u000a margin: 2px 0 0px 10px;\u000a width: 98%;\u000a overflow: auto;\u000a }\u000a\u000a .detailView select {\u000a font-size: 12px;\u000a padding: 4px 2px;\u000a border: solid 1px #aacfe4;\u000a margin: 2px 0 0px 10px;\u000a }\u000a\u000a .detailView .label {\u000a vertical-align: top;\u000a }\u000a\u000a .detailArrayLabel {\u000a font-size: medium;\u000a }\u000a\u000a .detailArrayLabel .foamTable {\u000a margin: 1px;\u000a width: 99%;\u000a }\u000a "}]}) CLASS({"package": "foam.ui","name": "IntFieldView","extendsModel": "foam.ui.AbstractNumberFieldView","methods": [{"name": "textToValue","code": function (text) { return parseInt(text) || '0'; }},{"name": "valueToText","code": function (value) { return value ? value : '0'; }}]}) CLASS({"package": "foam.ui","name": "AbstractNumberFieldView","extendsModel": "foam.ui.TextFieldView","properties": [{"name": "type","defaultValue": "number"},{"name": "step"}],"methods": [{"name": "extraAttributes","code": function () { return this.step ? ' step="' + this.step + '"' : ''; }}]}) CLASS({"package": "foam.ui","name": "FloatFieldView","extendsModel": "foam.ui.AbstractNumberFieldView","properties": [{"name": "precision","defaultValue": ""}],"methods": [{"name": "formatNumber","code": function (val) { if ( ! val ) return '0'; val = val.toFixed(this.precision); var i = val.length-1; for ( ; i > 0 && val.charAt(i) === '0' ; i-- ); return val.substring(0, val.charAt(i) === '.' ? i : i+1); }},{"name": "valueToText","code": function (val) { return this.hasOwnProperty('precision') ? this.formatNumber(val) : '' + val ; }},{"name": "textToValue","code": function (text) { return parseFloat(text) || 0; }}]}) CLASS({"package": "foam.ui","name": "DAOController","label": "DAO Controller","extendsModel": "foam.ui.View","properties": [{model_:"ModelProperty","name": "model"},{"name": "subType","setter": function (v) { this.model = v; }},{"name": "dao","view": "foam.ui.TableView"},{"name": "data","getter": function () { return this.dao; },"setter": function (v) { this.dao = v; }},{"name": "selection"},{model_:"BooleanProperty","name": "useSearchView","defaultValue": false}],"actions": [{"name": "new","help": "Create a new record.","action": function () { var createView = this.X.DAOCreateController.create({ model: this.model, dao: this.dao, showActions: true }); createView.parentController = this; this.X.stack.pushView(createView, 'New'); }},{"name": "edit","help": "Edit the current record.","default": "true","action": function () { // Todo: fix, should already be connected this.selection = this.daoView.selection; var obj = this.selection; var actions = this.X.DAOUpdateController.actions.slice(0); for ( var i = 0 ; i < this.model.actions.length ; i++ ) { var action = this.model.actions[i]; var newAction = this.X.Action.create(action); newAction.action = function (oldAction) { return function() { oldAction.call(obj); }; }(action.action); actions.push(newAction); } console.log(["selection: ", this.selection]); var updateView = this.X.DAOUpdateController.create({ data: this.selection/*.deepClone()*/, model: this.model, dao: this.dao, showActions: true }); this.X.stack.pushView(updateView, 'Edit'); }},{"name": "delete","help": "Delete the current record.","action": function () { // Todo: fix, should already be connected this.selection = this.daoView.selection; var self = this; this.dao.remove(this.selection); }}],"methods": [{"name": "init","code": function () { this.SUPER(); this.showActions = true; }},{"name": "initHTML","code": function () { this.SUPER(); this.daoView.subscribe(this.daoView.DOUBLE_CLICK, this.onDoubleClick); this.daoView.selection$.addListener(this.onSelection); }}],"listeners": [{"name": "onDoubleClick","code": function (evt) { for ( var i = 0 ; i < this.model_.actions.length ; i++ ) { var action = this.model_.actions[i]; if ( action.default ) { action.action.call(this); break; } } }},{"name": "onSelection","code": function (evt) { var obj = this.daoView.selection; if ( ! obj ) return; this.X.stack.setPreview( this.X.SummaryView.create({ model: this.model, data: this.daoView.selection })); }}],"templates": [{"name": "toInnerHTML","template": " $$dao{ model: this.model } "}]}) CLASS({"package": "foam.ui","name": "ActionButton","extendsModel": "foam.ui.BaseView","traits": ["foam.ui.HTMLViewTrait"],"properties": [{"name": "action","postSet": function (old, nu) { old && old.removeListener(this.render) nu.addListener(this.render); }},{"name": "data"},{"name": "className","factory": function () { return 'actionButton actionButton-' + this.action.name; }},{"name": "tagName","defaultValue": "button"},{"name": "showLabel","defaultValueFn": function () { return this.action.showLabel; }},{"name": "label","defaultValueFn": function () { return this.data ? this.action.labelFn.call(this.data, this.action) : this.action.label; }},{"name": "iconUrl","defaultValueFn": function () { return this.action.iconUrl; }},{"name": "tooltip","defaultValueFn": function () { return this.action.help; }}],"methods": [{"name": "toHTML","code": function () { var superResult = this.SUPER(); // get the destructors done before doing our work var self = this; this.on('click', function() { self.action.maybeCall(self.X, self.data); }, this.id); this.setAttribute('disabled', function() { self.closeTooltip(); return self.action.isEnabled.call(self.data, self.action) ? undefined : 'disabled'; }, this.id); this.setClass('available', function() { self.closeTooltip(); return self.action.isAvailable.call(self.data, self.action); }, this.id); this.X.dynamic(function() { self.action.labelFn.call(self.data, self.action); self.updateHTML(); }); return superResult; }},{"name": "toInnerHTML","code": function () { var out = ''; if ( this.iconUrl ) { out += '<img src="' + XMLUtil.escapeAttr(this.iconUrl) + '">'; } if ( this.showLabel ) { out += this.label; } return out; }},{"name": "initKeyboardShortcuts","code": function () { /* Not needed, will be done by parent View. */ }}],"listeners": [{"name": "render","code": function () { this.updateHTML(); },"isFramed": true}]})
src/components/link-repo.js
ReactJS-BA/meetup-2016-04-05
import React from 'react'; import {Link} from 'react-router'; class LinkRepo extends React.Component { render() { let url = this.props.repo.owner.login + '/' + this.props.repo.name; return ( <Link to={url} className="repo-link"> <h2>{url}</h2> <p>{this.props.repo.description}</p> <p><small>{this.props.repo.watchers_count} Watchers</small></p> </Link> ); } }; export default LinkRepo;
src/layouts/CoreLayout.js
seespace/dota2assistant
import React from 'react' // Note: Stateless/function components *will not* hot reload! // react-transform *only* works on component classes. // // Since layouts rarely change, they are a good place to // leverage React's new Statelesss Functions: // https://facebook.github.io/react/docs/reusable-components.html#stateless-functions // // CoreLayout is a pure function of it's props, so we can // define it with a plain javascript function... function CoreLayout ({ children }) { return ( <div className='container stackable'> {children} </div> ) } CoreLayout.propTypes = { children: React.PropTypes.element } export default CoreLayout
src/app.js
OssamaZ/canvas-play
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import Application from './containers/Application'; import configureStore from './store/configureStore'; // Initial state let _initialState; try { let _savedStateInstance = localStorage.getItem('canvas-playground') _initialState = _savedStateInstance ? JSON.parse(_savedStateInstance) : {}; } catch (e) {}; const store = configureStore(_initialState); store.subscribe(() => { // I'm only persisting the canvasComponents piece of my state .. just a choice i made localStorage.setItem('canvas-playground', JSON.stringify({ canvasComponents: store.getState().canvasComponents.present })); }); // Exporting store is fine as long as you keep the state immutable export default store; render( <Provider store={store}> <Application /> </Provider>, document.getElementById('main-container') );
src/js/components/Keyboard/stories/OnDocument.js
HewlettPackard/grommet
import React from 'react'; import { Box, Grommet, Heading, Keyboard } from 'grommet'; import { grommet } from 'grommet/themes'; export const OnDocument = () => ( <Grommet theme={grommet}> {/* eslint-disable no-alert */} <Keyboard target="document" onEsc={() => alert('You pressed Esc!')}> <Box pad="large" background="light-4"> <Heading level="3">Press Esc on me!</Heading> </Box> </Keyboard> </Grommet> ); OnDocument.parameters = { chromatic: { disable: true }, }; export default { title: 'Utilities/Keyboard/On Document', };
src/interface/icons/Uptime.js
yajinni/WoWAnalyzer
import React from 'react'; // https://thenounproject.com/term/duration/370713/ // duration by Bohdan Burmich from the Noun Project const Icon = ({ ...other }) => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="10 10 80 80" className="icon" {...other}> <path d="M50,86.4865c17.4361,0,31.6216-14.1855,31.6216-31.6216c0-16.6168-12.8865-30.2714-29.1892-31.5189v-4.9677h7.2973v-4.8649 H40.2703v4.8649h7.2973v4.9677c-16.3027,1.2475-29.1892,14.902-29.1892,31.5189C18.3784,72.3009,32.5639,86.4865,50,86.4865z M52.4324,28.2236c3.1101,0.2817,6.0664,1.0982,8.7798,2.356l-8.7798,15.2073V28.2236z M47.5676,28.2236v26.6412 c0,1.1008,0.7393,2.0647,1.8029,2.3497c0.209,0.0561,0.4205,0.0827,0.6295,0.0827c0.8533,0,1.6642-0.4504,2.1065-1.2162 l13.3146-23.0616c6.8507,4.8503,11.3357,12.8315,11.3357,21.8454c0,14.7537-12.0031,26.7567-26.7568,26.7567 s-26.7568-12.003-26.7568-26.7567C23.2432,40.9315,33.9501,29.4573,47.5676,28.2236z" /> </svg> ); export default Icon;
app/components/Spinner.js
codinglawyer/What-To-Cook-App
import React from 'react' import ReactLoading from 'react-loading' const Spinner = () => ( <ReactLoading type="bars" color="#444" className="createLoader" /> ) export default Spinner
src/constants/ActionTypes.js
royriojas/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import keyMirror from 'fbjs/lib/keyMirror'; export default keyMirror({ });
app/components/steps/SelectAmount.js
rolandaugusto/react-atm-simulator
import React from 'react'; import styles from './../../App.css'; import classnames from 'classnames'; import {steps as STEPS} from './../../steps'; let shakeTimeout; // This Class behaves almost the same as EnterPIN. In fact we could extend both classes from a more general // class. export default class SelectAmount extends React.Component { constructor(props) { super(props); this.state = { inputValue: '', customAmountActive: false, mustShake: false, errorMessage: '' }; this.nextStep = this.nextStep.bind(this); this.toggleCustomAmount = this.toggleCustomAmount.bind(this); this.validateAmount = this.validateAmount.bind(this); this.updateValue = this.updateValue.bind(this); this.clearInput = this.clearInput.bind(this); this.addNumberFromPad = this.addNumberFromPad.bind(this); } componentDidMount() { window.addEventListener('enter', this.validateAmount); window.addEventListener('clear', this.clearInput); window.addEventListener('number', this.addNumberFromPad); } componentWillUnmount() { window.removeEventListener('enter', this.validateAmount); window.removeEventListener('clear', this.clearInput); window.removeEventListener('number', this.addNumberFromPad); clearTimeout(shakeTimeout); } updateValue(e) { this.setState({inputValue: e.target.value}) } clearInput() { this.setState({inputValue: ''}); } addNumberFromPad(e) { let currVal = this.state.inputValue.toString(); if (currVal.length === 4) return; let val = (currVal === '') ? e.detail : currVal.concat(e.detail); this.setState({inputValue: val}); } nextStep() { this.props.updateStep(STEPS.TAKE_YOUR_MONEY, 'The ATM is preparing to deliver the amount requested...'); } toggleCustomAmount() { this.setState({customAmountActive: !this.state.customAmountActive}); } validateAmount() { if (this.state.inputValue !== '' && (this.state.inputValue % 10) === 0) { this.nextStep(); } else { this.setState({errorMessage: 'Wrong Amount!'}); this.setState({mustShake: true}); shakeTimeout = setTimeout(() => this.setState({mustShake: false}), 500); } } render() { let defaulCssClasses = classnames({ [styles.amountDefault]: true, [styles.hidden]: this.state.customAmountActive }); let customCssClasses = classnames({ [styles.hidden]: !this.state.customAmountActive }); let errorMessagesCssClasses = classnames({ [styles.redText]: true, [styles.shake]: this.state.mustShake }); return ( <div className={styles.bap}> <button className={styles.buttonBack} onClick={() => this.props.previousStep()} > BACK </button> Select the Amount to Withdraw <div className={defaulCssClasses}> <div className={styles.panelLeft}> <button className={styles.buttonAmount} onClick={this.nextStep}>20</button> <button className={styles.buttonAmount} onClick={this.nextStep}>80</button> <button className={styles.buttonAmount} onClick={this.nextStep}>200</button> </div> <div className={styles.panelRight}> <button className={styles.buttonAmount} onClick={this.nextStep}>40</button> <button className={styles.buttonAmount} onClick={this.nextStep}>100</button> <button className={styles.buttonAmount} onClick={this.toggleCustomAmount}>Other</button> </div> </div> <div className={customCssClasses}> { this.state.errorMessage !== '' ? <p className={errorMessagesCssClasses}>{this.state.errorMessage}</p> : '' } <p> <input className={styles.input} placeholder='0.00' onChange={this.updateValue} type='text' autoComplete='off' value={this.state.inputValue} required /> </p> </div> </div> ); } }
packages/material-ui-icons/src/PieChartSharp.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M11 2v20c-5.07-.5-9-4.79-9-10s3.93-9.5 9-10zm2.03 0v8.99H22c-.47-4.74-4.24-8.52-8.97-8.99zm0 11.01V22c4.74-.47 8.5-4.25 8.97-8.99h-8.97z" /> , 'PieChartSharp');
src/components/Book/index.js
jongold/goldOS
import React from 'react'; const Book = ({ item }) => { const width = 100; const height = 128; const viewBox = [0, 0, width, height].join(' '); const d = 'M93,8h-7H7H6C4.9,8,4,7.1,4,6c0-1.1,0.9-2,2-2h74V0H6C2.7,0,0,2.7,0,6v10.5V121c0,3.9,3.1,7,7,7h86c3.9,0,7-3.1,7-7V15C100,11.1,96.9,8,93,8z'; return ( <div className="mr2 mb2 relative"> <a href={item.get('url')}> <svg width={width} height={height} viewBox={viewBox} xmlns="http://www.w3.org/2000/svg" > <path className="fill-gold" d={d} /> </svg> <span className="absolute h6 white left-0 right-0 center mt3"> {item.get('title')} </span> </a> </div> ); }; export default Book;
GitHubFinder/src/components/TodoList/TodoList.js
Louis0503/TestRact
import React from 'react'; const TodoList = ({ todos, onDeleteTodo, }) => ( <div> <ul> { todos.map((todo, index) => ( <li key={index}> {todo.get('text')} <button onClick={onDeleteTodo(index)}>Delete</button> </li> )).toJS() } </ul> </div> ); export default TodoList;
src/components/Team/index.js
unihackhq/skilled-acolyte-frontend
import React from 'react'; import { Route } from 'react-router-dom'; import { observer, inject, PropTypes as MobxPropTypes } from 'mobx-react'; import { Message, MessageHeader, MessageBody, Box, Title } from 'bloomer'; import Loader from '../Loader'; import Page from '../Page'; import Invite from '../Invites/Invite'; import withLazyLoad from '../../utils/lazyLoad'; const TeamDetails = withLazyLoad(() => import('./TeamDetails')); const CreateTeam = withLazyLoad(() => import('./CreateTeam')); const EditTeam = withLazyLoad(() => import('./EditTeam')); class Team extends React.Component { static propTypes = { teams: MobxPropTypes.observableObject.isRequired, events: MobxPropTypes.observableObject.isRequired, invites: MobxPropTypes.observableObject.isRequired, } componentDidMount() { const { teams, invites } = this.props; teams.fetchList(); invites.fetchList(); } renderInvites = () => { const { invites, events } = this.props; const { loading } = invites; if (loading) { return <Loader inline />; } const eventInvites = invites.list.filter(invite => invite.eventId === events.selectedId); if (eventInvites.length > 0) { return ( <React.Fragment> <Title isSize={3} tag="h1">Invites</Title> {eventInvites.map(team => ( <Box key={team.id}> <Invite key={team.id} teamId={team.id} hasTeam={false} /> </Box> ))} </React.Fragment> ); } return null; } render() { const { teams, events } = this.props; const { loading, filterByEvent } = teams; if (loading) { return <Loader />; } // no event selected (probably still loading) if (!events.selectedId) { return null; } const eventTeams = filterByEvent(events.selected.id); if (eventTeams.length === 0) { return ( <Page> {this.renderInvites()} <CreateTeam /> </Page> ); } if (eventTeams.length > 1) { return ( <Page> <Title isSize={3} tag="h1">Your Teams</Title> <Message isColor="danger"> <MessageHeader>You can&apos;t be part of many teams!</MessageHeader> <MessageBody> <p>Looks like through some technical problem you have multiple teams!</p> <p>Please leave the extra teams.</p> </MessageBody> </Message> {eventTeams.map(team => <TeamDetails key={team.id} teamId={team.id} leaveOnly />)} </Page> ); } const teamId = eventTeams[0].id; return ( <Page> <Route exact path="/team/edit" component={() => <EditTeam teamId={teamId} />} /> <Route exact path="/team" component={() => <TeamDetails teamId={teamId} />} /> </Page> ); } } export default inject('teams', 'events', 'invites')(observer(Team));
Paths/React/05.Building Scalable React Apps/5-react-boilerplate-building-scalable-apps-m5-exercise-files/Before/app/components/Navigation/index.js
phiratio/Pluralsight-materials
/** * * Navigation * */ import React from 'react'; import styles from './styles.css'; function Navigation({ topics, selectTopic }) { const topicNodes = topics.map(t => ( <div key={t.name} onClick={() => selectTopic(t)} > {t.name} </div> )); return ( <div className={styles.navigation}> {topicNodes} </div> ); } Navigation.propTypes = { topics: React.PropTypes.arrayOf( React.PropTypes.shape({ name: React.PropTypes.string.isRequired, description: React.PropTypes.string.isRequired, }) ).isRequired, selectTopic: React.PropTypes.func.isRequired, }; export default Navigation;
src/styles/themeDecorator.js
pradel/material-ui
import React from 'react'; import warning from 'warning'; export default (customTheme) => { warning(false, 'ThemeDecorator is deprecated, please use MuiThemeProvider instead.'); return function(Component) { return React.createClass({ childContextTypes: { muiTheme: React.PropTypes.object.isRequired, }, getChildContext() { return { muiTheme: customTheme, }; }, render() { return React.createElement(Component, this.props); }, }); }; };
ajax/libs/yui/3.3.0/loader/loader-base-debug.js
dylannnn/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-2010.12.16-18-24', TNT = '2in3', TNT_VERSION = '4', YUI2_VERSION = '2.8.2', 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: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </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: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </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); delete m.expanded; } } 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]; // key = mod1 + mod2; // if (this.tested[key]) { // return this.tested[key]; // } // if (loaded[mod2] || !m || !other) { 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)) { // Y.log('group: ' + 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 }); // Y.log('adding skin ' + name + ', ' // + parent + ', ' + pkg + ', ' + info[name].path); } } 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> * </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); } // Y.log('pack ' + packName + ' should supersede ' + supName); // 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); } // Y.log('pack ' + packName + ' should supersede ' + 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) { // Y.log('returning no reqs for ' + mod.name); 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, hash; // 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; } // if (mod.expanded && (!mod.langCache || mod.langCache == this.lang)) { if (mod.expanded && (!this.lang || mod.langCache === this.lang)) { // Y.log('already expanded ' + name + ', ' + mod.expanded); return mod.expanded; } d = []; hash = {}; r = mod.requires; o = mod.optional; // Y.log("getRequires: " + name + " (dirty:" + this.dirty + // ", expanded:" + mod.expanded + ")"); mod._parsed = true; for (i = 0; i < r.length; i++) { // Y.log(name + ' requiring ' + r[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) { 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); // Y.log('conditional', m); 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); // Y.log('Best lang: ' + lang + ', this.lang: ' + // this.lang + ', mod.lang: ' + mod.lang); mod.langCache = this.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)); } } }); // Y.log('After explode: ' + YObject.keys(r)); }, 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) { // Y.log('testing patterns ' + YObject.keys(patterns)); for (pname in patterns) { if (patterns.hasOwnProperty(pname)) { // Y.log('testing pattern ' + i); 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) { // Y.log('executing pattern action: ' + pname); p.action.call(this, mname, pname); } else { Y.log('Undefined module: ' + mname + ', matched a pattern: ' + pname, 'info', 'loader'); // 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]]; } } } } } // Y.log('required now: ' + YObject.keys(r)); return r; }, _finish: function(msg, success) { Y.log('loader finishing: ' + msg + ', ' + Y.id + ', ' + this.data, 'info', 'loader'); _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) { Y.log('load error: ' + o.msg + ', ' + Y.id, 'error', 'loader'); 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() { Y.log('loader timeout: ' + Y.id, 'error', 'loader'); 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) { // Y.log('private _insert() ' + (type || '') + ', ' + Y.id, "info", "loader"); // 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; // Y.log("trying to load css first"); 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) { // Y.log('public insert() ' + (type || '') + ', ' + // Y.Object.keys(this.required), "info", "loader"); 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) { Y.log('Attempting to use combo: ' + combining, 'info', 'loader'); // 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; } // Y.log("loadNext executing, just loaded " + mname + ", " + // Y.id, "info", "loader"); // 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) { Y.log('still loading ' + s[i] + ', waiting', 'info', 'loader'); return; } // log("inserting " + s[i]); m = self.getModule(s[i]); if (!m) { if (!self.skipped[s[i]]) { msg = 'Undefined module ' + s[i] + ' skipped'; Y.log(msg, 'warn', 'loader'); // 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]; Y.log('attempting to load ' + s[i] + ', ' + self.base, 'info', 'loader'); 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) { // Y.log('loader internal'); self._internalCallback = null; fn.call(self); } else { // Y.log('loader complete'); 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']});
src/svg-icons/hardware/devices-other.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareDevicesOther = (props) => ( <SvgIcon {...props}> <path d="M3 6h18V4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V6zm10 6H9v1.78c-.61.55-1 1.33-1 2.22s.39 1.67 1 2.22V20h4v-1.78c.61-.55 1-1.34 1-2.22s-.39-1.67-1-2.22V12zm-2 5.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM22 8h-6c-.5 0-1 .5-1 1v10c0 .5.5 1 1 1h6c.5 0 1-.5 1-1V9c0-.5-.5-1-1-1zm-1 10h-4v-8h4v8z"/> </SvgIcon> ); HardwareDevicesOther = pure(HardwareDevicesOther); HardwareDevicesOther.displayName = 'HardwareDevicesOther'; HardwareDevicesOther.muiName = 'SvgIcon'; export default HardwareDevicesOther;
packages/material-ui-icons/src/Code.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Code = props => <SvgIcon {...props}> <path d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z" /> </SvgIcon>; Code = pure(Code); Code.muiName = 'SvgIcon'; export default Code;
webapp-src/src/callback.js
babelouest/glewlwyd
/** * * Glewlwyd login application * * Web application for users to login to Glewlwyd * Handle password and schemes authentication * * Copyright 2019 Nicolas Mora <mail@babelouest.org> * */ import React from 'react'; import ReactDOM from 'react-dom'; import i18next from 'i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; import apiManager from './lib/APIManager'; import App from './Callback/App'; import ErrorConfig from './lib/ErrorConfig'; function getUrlParams(search) { if (search) { const hashes = search.split('&'); const params = {}; hashes.map(hash => { const [key, val] = hash.split('='); params[key] = decodeURIComponent(val); }) return params; } else { return {}; } } var initApp = () => { apiManager.request("config.json") .then((frontEndConfig) => { if (!frontEndConfig.lang) { frontEndConfig.lang = ["en","fr","nl","de"]; } apiManager.request(frontEndConfig.GlewlwydUrl + "config/") .then((serverConfig) => { apiManager.setConfig(frontEndConfig.GlewlwydUrl + serverConfig.api_prefix); var config = Object.assign({ params: { state: getUrlParams(window.location.href.split('?')[1]).state||getUrlParams(window.location.hash.substring(1)).state||false } }, frontEndConfig, serverConfig); ReactDOM.render(<App config={config}/>, document.getElementById('root')); }) .fail((error) => { ReactDOM.render(<App config={false}/>, document.getElementById('root')); }); }) .fail((error) => { ReactDOM.render(<ErrorConfig/>, document.getElementById('root')); }); } var i18nextOpt = { fallbackLng: 'en', ns: ['translations'], defaultNS: 'translations', backend: { loadPath: 'locales/{{lng}}/{{ns}}.json' } }; if (getUrlParams(window.location.href.split('?')[1]).ui_locales) { i18nextOpt.lng = getUrlParams(window.location.href.split('?')[1]).ui_locales.split(" ")[0]; } try { i18next .use(Backend) .use(LanguageDetector) .init(i18nextOpt) .then(() => { initApp(); }); } catch (e) { $("#root").html('<div class="alert alert-danger" role="alert">' + '<i class="fas fa-exclamation-triangle"></i>' + '<span class="btn-icon-right">You must use a browser compatible with Glewlwyd SSO</span>' + '</div>'); }
src/svg-icons/av/equalizer.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvEqualizer = (props) => ( <SvgIcon {...props}> <path d="M10 20h4V4h-4v16zm-6 0h4v-8H4v8zM16 9v11h4V9h-4z"/> </SvgIcon> ); AvEqualizer = pure(AvEqualizer); AvEqualizer.displayName = 'AvEqualizer'; AvEqualizer.muiName = 'SvgIcon'; export default AvEqualizer;
src/svg-icons/action/search.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSearch = (props) => ( <SvgIcon {...props}> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/> </SvgIcon> ); ActionSearch = pure(ActionSearch); ActionSearch.displayName = 'ActionSearch'; ActionSearch.muiName = 'SvgIcon'; export default ActionSearch;
src/routes/dashboard/components/user.js
IssaTan1990/antd-admin
import React from 'react' import PropTypes from 'prop-types' import { Button } from 'antd' import styles from './user.less' import CountUp from 'react-countup' import { color } from '../../../utils' const countUpProps = { start: 0, duration: 2.75, useEasing: true, useGrouping: true, separator: ',', } function User ({ avatar, name, email, sales, sold }) { return (<div className={styles.user}> <div className={styles.header}> <div className={styles.headerinner}> <div className={styles.avatar} style={{ backgroundImage: `url(${avatar})` }} /> <h5 className={styles.name}>{name}</h5> <p>{email}</p> </div> </div> <div className={styles.number}> <div className={styles.item}> <p>EARNING SALES</p> <p style={{ color: color.green }}><CountUp end={sales} prefix="$" {...countUpProps} /></p> </div> <div className={styles.item}> <p>ITEM SOLD</p> <p style={{ color: color.blue }}><CountUp end={sold} {...countUpProps} /></p> </div> </div> <div className={styles.footer}> <Button type="ghost" size="large">View Profile</Button> </div> </div>) } User.propTypes = { avatar: PropTypes.string, name: PropTypes.string, email: PropTypes.string, sales: PropTypes.number, sold: PropTypes.number, } export default User
src/svg-icons/notification/rv-hookup.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationRvHookup = (props) => ( <SvgIcon {...props}> <path d="M20 17v-6c0-1.1-.9-2-2-2H7V7l-3 3 3 3v-2h4v3H4v3c0 1.1.9 2 2 2h2c0 1.66 1.34 3 3 3s3-1.34 3-3h8v-2h-2zm-9 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm7-6h-4v-3h4v3zM17 2v2H9v2h8v2l3-3z"/> </SvgIcon> ); NotificationRvHookup = pure(NotificationRvHookup); NotificationRvHookup.displayName = 'NotificationRvHookup'; NotificationRvHookup.muiName = 'SvgIcon'; export default NotificationRvHookup;
ajax/libs/ionic/0.9.26/js/ionic.js
masimakopoulos/cdnjs
/*! * Copyright 2014 Drifty Co. * http://drifty.com/ * * Ionic, v0.9.26 * A powerful HTML5 mobile app framework. * http://ionicframework.com/ * * By @maxlynch, @benjsperry, @adamdbradley <3 * * Licensed under the MIT license. Please see LICENSE for more information. * */ ; // Create namespaces // window.ionic = { controllers: {}, views: {}, version: '0.9.26' }; ; (function(ionic) { var bezierCoord = function (x,y) { if(!x) x=0; if(!y) y=0; return {x: x, y: y}; }; function B1(t) { return t*t*t; } function B2(t) { return 3*t*t*(1-t); } function B3(t) { return 3*t*(1-t)*(1-t); } function B4(t) { return (1-t)*(1-t)*(1-t); } ionic.Animator = { // Quadratic bezier solver getQuadraticBezier: function(percent,C1,C2,C3,C4) { var pos = new bezierCoord(); pos.x = C1.x*B1(percent) + C2.x*B2(percent) + C3.x*B3(percent) + C4.x*B4(percent); pos.y = C1.y*B1(percent) + C2.y*B2(percent) + C3.y*B3(percent) + C4.y*B4(percent); return pos; }, // Cubic bezier solver from https://github.com/arian/cubic-bezier (MIT) getCubicBezier: function(x1, y1, x2, y2, duration) { // Precision epsilon = (1000 / 60 / duration) / 4; var curveX = function(t){ var v = 1 - t; return 3 * v * v * t * x1 + 3 * v * t * t * x2 + t * t * t; }; var curveY = function(t){ var v = 1 - t; return 3 * v * v * t * y1 + 3 * v * t * t * y2 + t * t * t; }; var derivativeCurveX = function(t){ var v = 1 - t; return 3 * (2 * (t - 1) * t + v * v) * x1 + 3 * (- t * t * t + 2 * v * t) * x2; }; return function(t) { var x = t, t0, t1, t2, x2, d2, i; // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; i++){ x2 = curveX(t2) - x; if (Math.abs(x2) < epsilon) return curveY(t2); d2 = derivativeCurveX(t2); if (Math.abs(d2) < 1e-6) break; t2 = t2 - x2 / d2; } t0 = 0, t1 = 1, t2 = x; if (t2 < t0) return curveY(t0); if (t2 > t1) return curveY(t1); // Fallback to the bisection method for reliability. while (t0 < t1){ x2 = curveX(t2); if (Math.abs(x2 - x) < epsilon) return curveY(t2); if (x > x2) t0 = t2; else t1 = t2; t2 = (t1 - t0) * 0.5 + t0; } // Failure return curveY(t2); }; }, animate: function(element, className, fn) { return { leave: function() { var endFunc = function() { element.classList.remove('leave'); element.classList.remove('leave-active'); element.removeEventListener('webkitTransitionEnd', endFunc); element.removeEventListener('transitionEnd', endFunc); }; element.addEventListener('webkitTransitionEnd', endFunc); element.addEventListener('transitionEnd', endFunc); element.classList.add('leave'); element.classList.add('leave-active'); return this; }, enter: function() { var endFunc = function() { element.classList.remove('enter'); element.classList.remove('enter-active'); element.removeEventListener('webkitTransitionEnd', endFunc); element.removeEventListener('transitionEnd', endFunc); }; element.addEventListener('webkitTransitionEnd', endFunc); element.addEventListener('transitionEnd', endFunc); element.classList.add('enter'); element.classList.add('enter-active'); return this; } }; } }; })(ionic); ; (function(ionic) { var readyCallbacks = [], domReady = function() { for(var x=0; x<readyCallbacks.length; x++) { ionic.requestAnimationFrame(readyCallbacks[x]); } readyCallbacks = []; document.removeEventListener('DOMContentLoaded', domReady); }; document.addEventListener('DOMContentLoaded', domReady); // From the man himself, Mr. Paul Irish. // The requestAnimationFrame polyfill // Put it on window just to preserve its context // without having to use .call window._rAF = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 16); }; })(); ionic.DomUtil = { //Call with proper context requestAnimationFrame: function(cb) { window._rAF(cb); }, /* * When given a callback, if that callback is called 100 times between * animation frames, Throttle will make it only call the last of 100tha call * * It returns a function, which will then call the passed in callback. The * passed in callback will receive the context the returned function is called with. * * @example * this.setTranslateX = ionic.animationFrameThrottle(function(x) { * this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(' + x + 'px, 0, 0)'; * }) */ animationFrameThrottle: function(cb) { var args, isQueued, context; return function() { args = arguments; context = this; if (!isQueued) { isQueued = true; ionic.requestAnimationFrame(function() { cb.apply(context, args); isQueued = false; }); } }; }, /* * Find an element's offset, then add it to the offset of the parent * until we are at the direct child of parentEl * use-case: find scroll offset of any element within a scroll container */ getPositionInParent: function(el) { return { left: el.offsetLeft, top: el.offsetTop }; }, ready: function(cb) { if(document.readyState === "complete") { ionic.requestAnimationFrame(cb); } else { readyCallbacks.push(cb); } }, getTextBounds: function(textNode) { if(document.createRange) { var range = document.createRange(); range.selectNodeContents(textNode); if(range.getBoundingClientRect) { var rect = range.getBoundingClientRect(); if(rect) { var sx = window.scrollX; var sy = window.scrollY; return { top: rect.top + sy, left: rect.left + sx, right: rect.left + sx + rect.width, bottom: rect.top + sy + rect.height, width: rect.width, height: rect.height }; } } } return null; }, getChildIndex: function(element, type) { if(type) { var ch = element.parentNode.children; var c; for(var i = 0, k = 0, j = ch.length; i < j; i++) { c = ch[i]; if(c.nodeName && c.nodeName.toLowerCase() == type) { if(c == element) { return k; } k++; } } } return Array.prototype.slice.call(element.parentNode.children).indexOf(element); }, swapNodes: function(src, dest) { dest.parentNode.insertBefore(src, dest); }, /** * {returns} the closest parent matching the className */ getParentWithClass: function(e, className) { while(e.parentNode) { if(e.parentNode.classList && e.parentNode.classList.contains(className)) { return e.parentNode; } e = e.parentNode; } return null; }, /** * {returns} the closest parent or self matching the className */ getParentOrSelfWithClass: function(e, className) { while(e) { if(e.classList && e.classList.contains(className)) { return e; } e = e.parentNode; } return null; }, rectContains: function(x, y, x1, y1, x2, y2) { if(x < x1 || x > x2) return false; if(y < y1 || y > y2) return false; return true; } }; //Shortcuts ionic.requestAnimationFrame = ionic.DomUtil.requestAnimationFrame; ionic.animationFrameThrottle = ionic.DomUtil.animationFrameThrottle; })(window.ionic); ; /** * ion-events.js * * Author: Max Lynch <max@drifty.com> * * Framework events handles various mobile browser events, and * detects special events like tap/swipe/etc. and emits them * as custom events that can be used in an app. * * Portions lovingly adapted from github.com/maker/ratchet and github.com/alexgibson/tap.js - thanks guys! */ (function(ionic) { // Custom event polyfill if(!window.CustomEvent) { (function() { var CustomEvent; CustomEvent = function(event, params) { var evt; params = params || { bubbles: false, cancelable: false, detail: undefined }; try { evt = document.createEvent("CustomEvent"); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); } catch (error) { // fallback for browsers that don't support createEvent('CustomEvent') evt = document.createEvent("Event"); for (var param in params) { evt[param] = params[param]; } evt.initEvent(event, params.bubbles, params.cancelable); } return evt; }; CustomEvent.prototype = window.Event.prototype; window.CustomEvent = CustomEvent; })(); } ionic.EventController = { VIRTUALIZED_EVENTS: ['tap', 'swipe', 'swiperight', 'swipeleft', 'drag', 'hold', 'release'], // Trigger a new event trigger: function(eventType, data, bubbles, cancelable) { var event = new CustomEvent(eventType, { detail: data, bubbles: !!bubbles, cancelable: !!cancelable }); // Make sure to trigger the event on the given target, or dispatch it from // the window if we don't have an event target data && data.target && data.target.dispatchEvent(event) || window.dispatchEvent(event); }, // Bind an event on: function(type, callback, element) { var e = element || window; // Bind a gesture if it's a virtual event for(var i = 0, j = this.VIRTUALIZED_EVENTS.length; i < j; i++) { if(type == this.VIRTUALIZED_EVENTS[i]) { var gesture = new ionic.Gesture(element); gesture.on(type, callback); return gesture; } } // Otherwise bind a normal event e.addEventListener(type, callback); }, off: function(type, callback, element) { element.removeEventListener(type, callback); }, // Register for a new gesture event on the given element onGesture: function(type, callback, element) { var gesture = new ionic.Gesture(element); gesture.on(type, callback); return gesture; }, // Unregister a previous gesture event offGesture: function(gesture, type, callback) { gesture.off(type, callback); }, handlePopState: function(event) { }, }; // Map some convenient top-level functions for event handling ionic.on = function() { ionic.EventController.on.apply(ionic.EventController, arguments); }; ionic.off = function() { ionic.EventController.off.apply(ionic.EventController, arguments); }; ionic.trigger = ionic.EventController.trigger;//function() { ionic.EventController.trigger.apply(ionic.EventController.trigger, arguments); }; ionic.onGesture = function() { return ionic.EventController.onGesture.apply(ionic.EventController.onGesture, arguments); }; ionic.offGesture = function() { return ionic.EventController.offGesture.apply(ionic.EventController.offGesture, arguments); }; })(window.ionic); ; /** * Simple gesture controllers with some common gestures that emit * gesture events. * * Ported from github.com/EightMedia/hammer.js Gestures - thanks! */ (function(ionic) { /** * ionic.Gestures * use this to create instances * @param {HTMLElement} element * @param {Object} options * @returns {ionic.Gestures.Instance} * @constructor */ ionic.Gesture = function(element, options) { return new ionic.Gestures.Instance(element, options || {}); }; ionic.Gestures = {}; // default settings ionic.Gestures.defaults = { // add css to the element to prevent the browser from doing // its native behavior. this doesnt prevent the scrolling, // but cancels the contextmenu, tap highlighting etc // set to false to disable this stop_browser_behavior: 'disable-user-behavior' }; // detect touchevents ionic.Gestures.HAS_POINTEREVENTS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled; ionic.Gestures.HAS_TOUCHEVENTS = ('ontouchstart' in window); // dont use mouseevents on mobile devices ionic.Gestures.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android|silk/i; ionic.Gestures.NO_MOUSEEVENTS = ionic.Gestures.HAS_TOUCHEVENTS && window.navigator.userAgent.match(ionic.Gestures.MOBILE_REGEX); // eventtypes per touchevent (start, move, end) // are filled by ionic.Gestures.event.determineEventTypes on setup ionic.Gestures.EVENT_TYPES = {}; // direction defines ionic.Gestures.DIRECTION_DOWN = 'down'; ionic.Gestures.DIRECTION_LEFT = 'left'; ionic.Gestures.DIRECTION_UP = 'up'; ionic.Gestures.DIRECTION_RIGHT = 'right'; // pointer type ionic.Gestures.POINTER_MOUSE = 'mouse'; ionic.Gestures.POINTER_TOUCH = 'touch'; ionic.Gestures.POINTER_PEN = 'pen'; // touch event defines ionic.Gestures.EVENT_START = 'start'; ionic.Gestures.EVENT_MOVE = 'move'; ionic.Gestures.EVENT_END = 'end'; // hammer document where the base events are added at ionic.Gestures.DOCUMENT = window.document; // plugins namespace ionic.Gestures.plugins = {}; // if the window events are set... ionic.Gestures.READY = false; /** * setup events to detect gestures on the document */ function setup() { if(ionic.Gestures.READY) { return; } // find what eventtypes we add listeners to ionic.Gestures.event.determineEventTypes(); // Register all gestures inside ionic.Gestures.gestures for(var name in ionic.Gestures.gestures) { if(ionic.Gestures.gestures.hasOwnProperty(name)) { ionic.Gestures.detection.register(ionic.Gestures.gestures[name]); } } // Add touch events on the document ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_MOVE, ionic.Gestures.detection.detect); ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_END, ionic.Gestures.detection.detect); // ionic.Gestures is ready...! ionic.Gestures.READY = true; } /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * @param {HTMLElement} element * @param {Object} [options={}] * @returns {ionic.Gestures.Instance} * @name Gesture.Instance * @constructor */ ionic.Gestures.Instance = function(element, options) { var self = this; // A null element was passed into the instance, which means // whatever lookup was done to find this element failed to find it // so we can't listen for events on it. if(element === null) { console.error('Null element passed to gesture (element does not exist). Not listening for gesture'); return; } // setup ionic.GesturesJS window events and register all gestures // this also sets up the default options setup(); this.element = element; // start/stop detection option this.enabled = true; // merge options this.options = ionic.Gestures.utils.extend( ionic.Gestures.utils.extend({}, ionic.Gestures.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.stop_browser_behavior) { ionic.Gestures.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior); } // start detection on touchstart ionic.Gestures.event.onTouch(element, ionic.Gestures.EVENT_START, function(ev) { if(self.enabled) { ionic.Gestures.detection.startDetect(self, ev); } }); // return instance return this; }; ionic.Gestures.Instance.prototype = { /** * bind events to the instance * @param {String} gesture * @param {Function} handler * @returns {ionic.Gestures.Instance} */ on: function onEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t=0; t<gestures.length; t++) { this.element.addEventListener(gestures[t], handler, false); } return this; }, /** * unbind events to the instance * @param {String} gesture * @param {Function} handler * @returns {ionic.Gestures.Instance} */ off: function offEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t=0; t<gestures.length; t++) { this.element.removeEventListener(gestures[t], handler, false); } return this; }, /** * trigger gesture event * @param {String} gesture * @param {Object} eventData * @returns {ionic.Gestures.Instance} */ trigger: function triggerEvent(gesture, eventData){ // create DOM event var event = ionic.Gestures.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(ionic.Gestures.utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @param {Boolean} state * @returns {ionic.Gestures.Instance} */ enable: function enable(state) { this.enabled = state; return this; } }; /** * this holds the last move event, * used to fix empty touchend issue * see the onTouch event for an explanation * @type {Object} */ var last_move_event = null; /** * when the mouse is hold down, this is true * @type {Boolean} */ var enable_detect = false; /** * when touch events have been fired, this is true * @type {Boolean} */ var touch_triggered = false; ionic.Gestures.event = { /** * simple addEventListener * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ bindDom: function(element, type, handler) { var types = type.split(' '); for(var t=0; t<types.length; t++) { element.addEventListener(types[t], handler, false); } }, /** * touch events with mouse fallback * @param {HTMLElement} element * @param {String} eventType like ionic.Gestures.EVENT_MOVE * @param {Function} handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; this.bindDom(element, ionic.Gestures.EVENT_TYPES[eventType], function bindDomOnTouch(ev) { var sourceEventType = ev.type.toLowerCase(); // onmouseup, but when touchend has been fired we do nothing. // this is for touchdevices which also fire a mouseup on touchend if(sourceEventType.match(/mouse/) && touch_triggered) { return; } // mousebutton must be down or a touch event else if( sourceEventType.match(/touch/) || // touch events are always on screen sourceEventType.match(/pointerdown/) || // pointerevents touch (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed ){ enable_detect = true; } // mouse isn't pressed else if(sourceEventType.match(/mouse/) && ev.which !== 1) { enable_detect = false; } // we are in a touch event, set the touch triggered bool to true, // this for the conflicts that may occur on ios and android if(sourceEventType.match(/touch|pointer/)) { touch_triggered = true; } // count the total touches on the screen var count_touches = 0; // when touch has been triggered in this detection session // and we are now handling a mouse event, we stop that to prevent conflicts if(enable_detect) { // update pointerevent if(ionic.Gestures.HAS_POINTEREVENTS && eventType != ionic.Gestures.EVENT_END) { count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev); } // touch else if(sourceEventType.match(/touch/)) { count_touches = ev.touches.length; } // mouse else if(!touch_triggered) { count_touches = sourceEventType.match(/up/) ? 0 : 1; } // if we are in a end event, but when we remove one touch and // we still have enough, set eventType to move if(count_touches > 0 && eventType == ionic.Gestures.EVENT_END) { eventType = ionic.Gestures.EVENT_MOVE; } // no touches, force the end event else if(!count_touches) { eventType = ionic.Gestures.EVENT_END; } // store the last move event if(count_touches || last_move_event === null) { last_move_event = ev; } // trigger the handler handler.call(ionic.Gestures.detection, self.collectEventData(element, eventType, self.getTouchList(last_move_event, eventType), ev)); // remove pointerevent from list if(ionic.Gestures.HAS_POINTEREVENTS && eventType == ionic.Gestures.EVENT_END) { count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev); } } //debug(sourceEventType +" "+ eventType); // on the end we reset everything if(!count_touches) { last_move_event = null; enable_detect = false; touch_triggered = false; ionic.Gestures.PointerEvent.reset(); } }); }, /** * we have different events for each device/browser * determine what we need and set them in the ionic.Gestures.EVENT_TYPES constant */ determineEventTypes: function determineEventTypes() { // determine the eventtype we want to set var types; // pointerEvents magic if(ionic.Gestures.HAS_POINTEREVENTS) { types = ionic.Gestures.PointerEvent.getEvents(); } // on Android, iOS, blackberry, windows mobile we dont want any mouseevents else if(ionic.Gestures.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel']; } // for non pointer events browsers and mixed browsers, // like chrome on windows8 touch laptop else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup']; } ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_START] = types[0]; ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_MOVE] = types[1]; ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_END] = types[2]; }, /** * create touchlist depending on the event * @param {Object} ev * @param {String} eventType used by the fakemultitouch plugin */ getTouchList: function getTouchList(ev/*, eventType*/) { // get the fake pointerEvent touchlist if(ionic.Gestures.HAS_POINTEREVENTS) { return ionic.Gestures.PointerEvent.getTouchList(); } // get the touchlist else if(ev.touches) { return ev.touches; } // make fake touchlist from mouse position else { ev.indentifier = 1; return [ev]; } }, /** * collect event data for ionic.Gestures js * @param {HTMLElement} element * @param {String} eventType like ionic.Gestures.EVENT_MOVE * @param {Object} eventData */ collectEventData: function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = ionic.Gestures.POINTER_TOUCH; if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) { pointerType = ionic.Gestures.POINTER_MOUSE; } return { center : ionic.Gestures.utils.getCenter(touches), timeStamp : new Date().getTime(), target : ev.target, touches : touches, eventType : eventType, pointerType : pointerType, srcEvent : ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { if(this.srcEvent.preventManipulation) { this.srcEvent.preventManipulation(); } if(this.srcEvent.preventDefault) { //this.srcEvent.preventDefault(); } }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return ionic.Gestures.detection.stopDetect(); } }; } }; ionic.Gestures.PointerEvent = { /** * holds all pointers * @type {Object} */ pointers: {}, /** * get a list of pointers * @returns {Array} touchlist */ getTouchList: function() { var self = this; var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Object.keys(self.pointers).sort().forEach(function(id) { touchlist.push(self.pointers[id]); }); return touchlist; }, /** * update the position of a pointer * @param {String} type ionic.Gestures.EVENT_END * @param {Object} pointerEvent */ updatePointer: function(type, pointerEvent) { if(type == ionic.Gestures.EVENT_END) { this.pointers = {}; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } return Object.keys(this.pointers).length; }, /** * check if ev matches pointertype * @param {String} pointerType ionic.Gestures.POINTER_MOUSE * @param {PointerEvent} ev */ matchType: function(pointerType, ev) { if(!ev.pointerType) { return false; } var types = {}; types[ionic.Gestures.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == ionic.Gestures.POINTER_MOUSE); types[ionic.Gestures.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == ionic.Gestures.POINTER_TOUCH); types[ionic.Gestures.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == ionic.Gestures.POINTER_PEN); return types[pointerType]; }, /** * get events */ getEvents: function() { return [ 'pointerdown MSPointerDown', 'pointermove MSPointerMove', 'pointerup pointercancel MSPointerUp MSPointerCancel' ]; }, /** * reset the list */ reset: function() { this.pointers = {}; } }; ionic.Gestures.utils = { /** * extend method, * also used for cloning when dest is an empty object * @param {Object} dest * @param {Object} src * @parm {Boolean} merge do a merge * @returns {Object} dest */ extend: function extend(dest, src, merge) { for (var key in src) { if(dest[key] !== undefined && merge) { continue; } dest[key] = src[key]; } return dest; }, /** * find if a node is in the given parent * used for event delegation tricks * @param {HTMLElement} node * @param {HTMLElement} parent * @returns {boolean} has_parent */ hasParent: function(node, parent) { while(node){ if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @param {Array} touches * @returns {Object} center */ getCenter: function getCenter(touches) { var valuesX = [], valuesY = []; for(var t= 0,len=touches.length; t<len; t++) { valuesX.push(touches[t].pageX); valuesY.push(touches[t].pageY); } return { pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2), pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2) }; }, /** * calculate the velocity between two points * @param {Number} delta_time * @param {Number} delta_x * @param {Number} delta_y * @returns {Object} velocity */ getVelocity: function getVelocity(delta_time, delta_x, delta_y) { return { x: Math.abs(delta_x / delta_time) || 0, y: Math.abs(delta_y / delta_time) || 0 }; }, /** * calculate the angle between two coordinates * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} angle */ getAngle: function getAngle(touch1, touch2) { var y = touch2.pageY - touch1.pageY, x = touch2.pageX - touch1.pageX; return Math.atan2(y, x) * 180 / Math.PI; }, /** * angle to direction define * @param {Touch} touch1 * @param {Touch} touch2 * @returns {String} direction constant, like ionic.Gestures.DIRECTION_LEFT */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.pageX - touch2.pageX), y = Math.abs(touch1.pageY - touch2.pageY); if(x >= y) { return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } else { return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } }, /** * calculate the distance between two touches * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.pageX - touch1.pageX, y = touch2.pageY - touch1.pageY; return Math.sqrt((x*x) + (y*y)); }, /** * calculate the scale factor between two touchLists (fingers) * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start * @param {Array} end * @returns {Number} scale */ getScale: function getScale(start, end) { // need two fingers... if(start.length >= 2 && end.length >= 2) { return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]); } return 1; }, /** * calculate the rotation degrees between two touchLists (fingers) * @param {Array} start * @param {Array} end * @returns {Number} rotation */ getRotation: function getRotation(start, end) { // need two fingers if(start.length >= 2 && end.length >= 2) { return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]); } return 0; }, /** * boolean if the direction is vertical * @param {String} direction * @returns {Boolean} is_vertical */ isVertical: function isVertical(direction) { return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN); }, /** * stop browser default behavior with css class * @param {HtmlElement} element * @param {Object} css_class */ stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_class) { // changed from making many style changes to just adding a preset classname // less DOM manipulations, less code, and easier to control in the CSS side of things // hammer.js doesn't come with CSS, but ionic does, which is why we prefer this method if(element && element.classList) { element.classList.add(css_class); element.onselectstart = function() { return false; }; } } }; ionic.Gestures.detection = { // contains all registred ionic.Gestures.gestures in the correct order gestures: [], // data of the current ionic.Gestures.gesture detection session current: null, // the previous ionic.Gestures.gesture session data // is a full clone of the previous gesture.current object previous: null, // when this becomes true, no gestures are fired stopped: false, /** * start ionic.Gestures.gesture detection * @param {ionic.Gestures.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a ionic.Gestures.gesture detection on an element if(this.current) { return; } this.stopped = false; this.current = { inst : inst, // reference to ionic.GesturesInstance we're working for startEvent : ionic.Gestures.utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent : false, // last eventData name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * ionic.Gestures.gesture detection * @param {Object} eventData */ detect: function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // instance options var inst_options = this.current.inst.options; // call ionic.Gestures.gesture handlers for(var g=0,len=this.gestures.length; g<len; g++) { var gesture = this.gestures[g]; // only when the instance options have enabled this gesture if(!this.stopped && inst_options[gesture.name] !== false) { // if a handler returns false, we stop with the detection if(gesture.handler.call(gesture, eventData, this.current.inst) === false) { this.stopDetect(); break; } } } // store as previous event event if(this.current) { this.current.lastEvent = eventData; } // endevent, but not the last touch, so dont stop if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length-1) { this.stopDetect(); } return eventData; }, /** * clear the ionic.Gestures.gesture vars * this is called on endDetect, but can also be used when a final ionic.Gestures.gesture has been detected * to stop other ionic.Gestures.gestures from being fired */ stopDetect: function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = ionic.Gestures.utils.extend({}, this.current); // reset the current this.current = null; // stopped! this.stopped = true; }, /** * extend eventData for ionic.Gestures.gestures * @param {Object} ev * @returns {Object} ev */ extendEventData: function extendEventData(ev) { var startEv = this.current.startEvent; // if the touches change, set the new touches over the startEvent touches // this because touchevents don't have all the touches on touchstart, or the // user must place his fingers at the EXACT same time on the screen, which is not realistic // but, sometimes it happens that both fingers are touching at the EXACT same time if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) { // extend 1 level deep to get the touchlist with the touch objects startEv.touches = []; for(var i=0,len=ev.touches.length; i<len; i++) { startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i])); } } var delta_time = ev.timeStamp - startEv.timeStamp, delta_x = ev.center.pageX - startEv.center.pageX, delta_y = ev.center.pageY - startEv.center.pageY, velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y); ionic.Gestures.utils.extend(ev, { deltaTime : delta_time, deltaX : delta_x, deltaY : delta_y, velocityX : velocity.x, velocityY : velocity.y, distance : ionic.Gestures.utils.getDistance(startEv.center, ev.center), angle : ionic.Gestures.utils.getAngle(startEv.center, ev.center), direction : ionic.Gestures.utils.getDirection(startEv.center, ev.center), scale : ionic.Gestures.utils.getScale(startEv.touches, ev.touches), rotation : ionic.Gestures.utils.getRotation(startEv.touches, ev.touches), startEvent : startEv }); return ev; }, /** * register new gesture * @param {Object} gesture object, see gestures.js for documentation * @returns {Array} gestures */ register: function register(gesture) { // add an enable gesture options if there is no given var options = gesture.defaults || {}; if(options[gesture.name] === undefined) { options[gesture.name] = true; } // extend ionic.Gestures default options with the ionic.Gestures.gesture options ionic.Gestures.utils.extend(ionic.Gestures.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add ionic.Gestures.gesture to the list this.gestures.push(gesture); // sort the list by index this.gestures.sort(function(a, b) { if (a.index < b.index) { return -1; } if (a.index > b.index) { return 1; } return 0; }); return this.gestures; } }; ionic.Gestures.gestures = ionic.Gestures.gestures || {}; /** * Custom gestures * ============================== * * Gesture object * -------------------- * The object structure of a gesture: * * { name: 'mygesture', * index: 1337, * defaults: { * mygesture_option: true * } * handler: function(type, ev, inst) { * // trigger gesture event * inst.trigger(this.name, ev); * } * } * @param {String} name * this should be the name of the gesture, lowercase * it is also being used to disable/enable the gesture per instance config. * * @param {Number} [index=1000] * the index of the gesture, where it is going to be in the stack of gestures detection * like when you build an gesture that depends on the drag gesture, it is a good * idea to place it after the index of the drag gesture. * * @param {Object} [defaults={}] * the default settings of the gesture. these are added to the instance settings, * and can be overruled per instance. you can also add the name of the gesture, * but this is also added by default (and set to true). * * @param {Function} handler * this handles the gesture detection of your custom gesture and receives the * following arguments: * * @param {Object} eventData * event data containing the following properties: * timeStamp {Number} time the event occurred * target {HTMLElement} target element * touches {Array} touches (fingers, pointers, mouse) on the screen * pointerType {String} kind of pointer that was used. matches ionic.Gestures.POINTER_MOUSE|TOUCH * center {Object} center position of the touches. contains pageX and pageY * deltaTime {Number} the total time of the touches in the screen * deltaX {Number} the delta on x axis we haved moved * deltaY {Number} the delta on y axis we haved moved * velocityX {Number} the velocity on the x * velocityY {Number} the velocity on y * angle {Number} the angle we are moving * direction {String} the direction we are moving. matches ionic.Gestures.DIRECTION_UP|DOWN|LEFT|RIGHT * distance {Number} the distance we haved moved * scale {Number} scaling of the touches, needs 2 touches * rotation {Number} rotation of the touches, needs 2 touches * * eventType {String} matches ionic.Gestures.EVENT_START|MOVE|END * srcEvent {Object} the source event, like TouchStart or MouseDown * * startEvent {Object} contains the same properties as above, * but from the first touch. this is used to calculate * distances, deltaTime, scaling etc * * @param {ionic.Gestures.Instance} inst * the instance we are doing the detection for. you can get the options from * the inst.options object and trigger the gesture event by calling inst.trigger * * * Handle gestures * -------------------- * inside the handler you can get/set ionic.Gestures.detectionic.current. This is the current * detection sessionic. It has the following properties * @param {String} name * contains the name of the gesture we have detected. it has not a real function, * only to check in other gestures if something is detected. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can * check if the current gesture is 'drag' by accessing ionic.Gestures.detectionic.current.name * * @readonly * @param {ionic.Gestures.Instance} inst * the instance we do the detection for * * @readonly * @param {Object} startEvent * contains the properties of the first gesture detection in this sessionic. * Used for calculations about timing, distance, etc. * * @readonly * @param {Object} lastEvent * contains all the properties of the last gesture detect in this sessionic. * * after the gesture detection session has been completed (user has released the screen) * the ionic.Gestures.detectionic.current object is copied into ionic.Gestures.detectionic.previous, * this is usefull for gestures like doubletap, where you need to know if the * previous gesture was a tap * * options that have been set by the instance can be received by calling inst.options * * You can trigger a gesture event by calling inst.trigger("mygesture", event). * The first param is the name of your gesture, the second the event argument * * * Register gestures * -------------------- * When an gesture is added to the ionic.Gestures.gestures object, it is auto registered * at the setup of the first ionic.Gestures instance. You can also call ionic.Gestures.detectionic.register * manually and pass your gesture object as a param * */ /** * Hold * Touch stays at the same place for x time * @events hold */ ionic.Gestures.gestures.Hold = { name: 'hold', index: 10, defaults: { hold_timeout : 500, hold_threshold : 1 }, timer: null, handler: function holdGesture(ev, inst) { switch(ev.eventType) { case ionic.Gestures.EVENT_START: // clear any running timers clearTimeout(this.timer); // set the gesture so we can check in the timeout if it still is ionic.Gestures.detection.current.name = this.name; // set timer and if after the timeout it still is hold, // we trigger the hold event this.timer = setTimeout(function() { if(ionic.Gestures.detection.current.name == 'hold') { inst.trigger('hold', ev); } }, inst.options.hold_timeout); break; // when you move or end we clear the timer case ionic.Gestures.EVENT_MOVE: if(ev.distance > inst.options.hold_threshold) { clearTimeout(this.timer); } break; case ionic.Gestures.EVENT_END: clearTimeout(this.timer); break; } } }; /** * Tap/DoubleTap * Quick touch at a place or double at the same place * @events tap, doubletap */ ionic.Gestures.gestures.Tap = { name: 'tap', index: 100, defaults: { tap_max_touchtime : 250, tap_max_distance : 10, tap_always : true, doubletap_distance : 20, doubletap_interval : 300 }, handler: function tapGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { // previous gesture, for the double tap since these are two different gesture detections var prev = ionic.Gestures.detection.previous, did_doubletap = false; // when the touchtime is higher then the max touch time // or when the moving distance is too much if(ev.deltaTime > inst.options.tap_max_touchtime || ev.distance > inst.options.tap_max_distance) { return; } // check if double tap if(prev && prev.name == 'tap' && (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval && ev.distance < inst.options.doubletap_distance) { inst.trigger('doubletap', ev); did_doubletap = true; } // do a single tap if(!did_doubletap || inst.options.tap_always) { ionic.Gestures.detection.current.name = 'tap'; inst.trigger(ionic.Gestures.detection.current.name, ev); } } } }; /** * Swipe * triggers swipe events when the end velocity is above the threshold * @events swipe, swipeleft, swiperight, swipeup, swipedown */ ionic.Gestures.gestures.Swipe = { name: 'swipe', index: 40, defaults: { // set 0 for unlimited, but this can conflict with transform swipe_max_touches : 1, swipe_velocity : 0.7 }, handler: function swipeGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { // max touches if(inst.options.swipe_max_touches > 0 && ev.touches.length > inst.options.swipe_max_touches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > inst.options.swipe_velocity || ev.velocityY > inst.options.swipe_velocity) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * Drag * Move with x fingers (default 1) around on the page. Blocking the scrolling when * moving left and right is a good practice. When all the drag events are blocking * you disable scrolling on that area. * @events drag, drapleft, dragright, dragup, dragdown */ ionic.Gestures.gestures.Drag = { name: 'drag', index: 50, defaults: { drag_min_distance : 10, // Set correct_for_drag_min_distance to true to make the starting point of the drag // be calculated from where the drag was triggered, not from where the touch started. // Useful to avoid a jerk-starting drag, which can make fine-adjustments // through dragging difficult, and be visually unappealing. correct_for_drag_min_distance : true, // set 0 for unlimited, but this can conflict with transform drag_max_touches : 1, // prevent default browser behavior when dragging occurs // be careful with it, it makes the element a blocking element // when you are using the drag gesture, it is a good practice to set this true drag_block_horizontal : true, drag_block_vertical : true, // drag_lock_to_axis keeps the drag gesture on the axis that it started on, // It disallows vertical directions if the initial direction was horizontal, and vice versa. drag_lock_to_axis : false, // drag lock only kicks in when distance > drag_lock_min_distance // This way, locking occurs only when the distance has become large enough to reliably determine the direction drag_lock_min_distance : 25 }, triggered: false, handler: function dragGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(ionic.Gestures.detection.current.name != this.name && this.triggered) { inst.trigger(this.name +'end', ev); this.triggered = false; return; } // max touches if(inst.options.drag_max_touches > 0 && ev.touches.length > inst.options.drag_max_touches) { return; } switch(ev.eventType) { case ionic.Gestures.EVENT_START: this.triggered = false; break; case ionic.Gestures.EVENT_MOVE: // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.distance < inst.options.drag_min_distance && ionic.Gestures.detection.current.name != this.name) { return; } // we are dragging! if(ionic.Gestures.detection.current.name != this.name) { ionic.Gestures.detection.current.name = this.name; if (inst.options.correct_for_drag_min_distance) { // When a drag is triggered, set the event center to drag_min_distance pixels from the original event center. // Without this correction, the dragged distance would jumpstart at drag_min_distance pixels instead of at 0. // It might be useful to save the original start point somewhere var factor = Math.abs(inst.options.drag_min_distance/ev.distance); ionic.Gestures.detection.current.startEvent.center.pageX += ev.deltaX * factor; ionic.Gestures.detection.current.startEvent.center.pageY += ev.deltaY * factor; // recalculate event data using new start point ev = ionic.Gestures.detection.extendEventData(ev); } } // lock drag to axis? if(ionic.Gestures.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) { ev.drag_locked_to_axis = true; } var last_direction = ionic.Gestures.detection.current.lastEvent.direction; if(ev.drag_locked_to_axis && last_direction !== ev.direction) { // keep direction on the axis that the drag gesture started on if(ionic.Gestures.utils.isVertical(last_direction)) { ev.direction = (ev.deltaY < 0) ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name +'start', ev); this.triggered = true; } // trigger normal event inst.trigger(this.name, ev); // direction event, like dragdown inst.trigger(this.name + ev.direction, ev); // block the browser events if( (inst.options.drag_block_vertical && ionic.Gestures.utils.isVertical(ev.direction)) || (inst.options.drag_block_horizontal && !ionic.Gestures.utils.isVertical(ev.direction))) { ev.preventDefault(); } break; case ionic.Gestures.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name +'end', ev); } this.triggered = false; break; } } }; /** * Transform * User want to scale or rotate with 2 fingers * @events transform, pinch, pinchin, pinchout, rotate */ ionic.Gestures.gestures.Transform = { name: 'transform', index: 45, defaults: { // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 transform_min_scale : 0.01, // rotation in degrees transform_min_rotation : 1, // prevent default browser behavior when two touches are on the screen // but it makes the element a blocking element // when you are using the transform gesture, it is a good practice to set this true transform_always_block : false }, triggered: false, handler: function transformGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(ionic.Gestures.detection.current.name != this.name && this.triggered) { inst.trigger(this.name +'end', ev); this.triggered = false; return; } // atleast multitouch if(ev.touches.length < 2) { return; } // prevent default when two fingers are on the screen if(inst.options.transform_always_block) { ev.preventDefault(); } switch(ev.eventType) { case ionic.Gestures.EVENT_START: this.triggered = false; break; case ionic.Gestures.EVENT_MOVE: var scale_threshold = Math.abs(1-ev.scale); var rotation_threshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scale_threshold < inst.options.transform_min_scale && rotation_threshold < inst.options.transform_min_rotation) { return; } // we are transforming! ionic.Gestures.detection.current.name = this.name; // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name +'start', ev); this.triggered = true; } inst.trigger(this.name, ev); // basic transform event // trigger rotate event if(rotation_threshold > inst.options.transform_min_rotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scale_threshold > inst.options.transform_min_scale) { inst.trigger('pinch', ev); inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev); } break; case ionic.Gestures.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name +'end', ev); } this.triggered = false; break; } } }; /** * Touch * Called as first, tells the user has touched the screen * @events touch */ ionic.Gestures.gestures.Touch = { name: 'touch', index: -Infinity, defaults: { // call preventDefault at touchstart, and makes the element blocking by // disabling the scrolling of the page, but it improves gestures like // transforming and dragging. // be careful with using this, it can be very annoying for users to be stuck // on the page prevent_default: false, // disable mouse events, so only touch (or pen!) input triggers events prevent_mouseevents: false }, handler: function touchGesture(ev, inst) { if(inst.options.prevent_mouseevents && ev.pointerType == ionic.Gestures.POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.prevent_default) { ev.preventDefault(); } if(ev.eventType == ionic.Gestures.EVENT_START) { inst.trigger(this.name, ev); } } }; /** * Release * Called as last, tells the user has released the screen * @events release */ ionic.Gestures.gestures.Release = { name: 'release', index: Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { inst.trigger(this.name, ev); } } }; })(window.ionic); ; (function(ionic) { ionic.Platform = { isReady: false, isFullScreen: false, platforms: null, grade: null, ua: navigator.userAgent, ready: function(cb) { // run through tasks to complete now that the device is ready if(this.isReady) { cb(); } else { // the platform isn't ready yet, add it to this array // which will be called once the platform is ready readyCallbacks.push(cb); } }, detect: function() { var i, bodyClass = document.body.className; ionic.Platform._checkPlatforms(); // only change the body class if we got platform info for(i = 0; i < this.platforms.length; i++) { bodyClass += ' platform-' + this.platforms[i]; } bodyClass += ' grade-' + this.grade; document.body.className = bodyClass.trim(); }, device: function() { if(window.device) return window.device; if(this.isCordova()) console.error('device plugin required'); return {}; }, _checkPlatforms: function(platforms) { this.platforms = []; this.grade = 'a'; if(this.isCordova()) this.platforms.push('cordova'); if(this.isIPad()) this.platforms.push('ipad'); var platform = this.platform(); if(platform) { this.platforms.push(platform); var version = this.version(); if(version) { var v = version.toString(); if(v.indexOf('.') > 0) { v = v.replace('.', '_'); } else { v += '_0'; } this.platforms.push(platform + v.split('_')[0]); this.platforms.push(platform + v); if(this.isAndroid() && version < 4.4) { this.grade = (version < 4 ? 'c' : 'b'); } } } }, // Check if we are running in Cordova isCordova: function() { return !(!window.cordova && !window.PhoneGap && !window.phonegap); }, isIPad: function() { return this.ua.toLowerCase().indexOf('ipad') >= 0; }, isIOS: function() { return this.is('ios'); }, isAndroid: function() { return this.is('android'); }, platform: function() { // singleton to get the platform name if(platformName === null) this.setPlatform(this.device().platform); return platformName; }, setPlatform: function(n) { if(typeof n != 'undefined' && n !== null && n.length) { platformName = n.toLowerCase(); } else if(this.ua.indexOf('Android') > 0) { platformName = 'android'; } else if(this.ua.indexOf('iPhone') > -1 || this.ua.indexOf('iPad') > -1 || this.ua.indexOf('iPod') > -1) { platformName = 'ios'; } else { platformName = 'unknown'; } }, version: function() { // singleton to get the platform version if(platformVersion === null) this.setVersion(this.device().version); return platformVersion; }, setVersion: function(v) { if(typeof v != 'undefined' && v !== null) { v = v.split('.'); v = parseFloat(v[0] + '.' + (v.length > 1 ? v[1] : 0)); if(!isNaN(v)) { platformVersion = v; return; } } platformVersion = 0; // fallback to user-agent checking var pName = this.platform(); var versionMatch = { 'android': /Android (\d+).(\d+)?/, 'ios': /OS (\d+)_(\d+)?/ }; if(versionMatch[pName]) { v = this.ua.match( versionMatch[pName] ); if(v.length > 2) { platformVersion = parseFloat( v[1] + '.' + v[2] ); } } }, // Check if the platform is the one detected by cordova is: function(type) { type = type.toLowerCase(); // check if it has an array of platforms if(this.platforms) { for(var x = 0; x < this.platforms.length; x++) { if(this.platforms[x] === type) return true; } } // exact match var pName = this.platform(); if(pName) { return pName === type.toLowerCase(); } // A quick hack for to check userAgent return this.ua.toLowerCase().indexOf(type) >= 0; }, exitApp: function() { this.ready(function(){ navigator.app && navigator.app.exitApp && navigator.app.exitApp(); }); }, showStatusBar: function(val) { // Only useful when run within cordova this.showStatusBar = val; this.ready(function(){ // run this only when or if the platform (cordova) is ready if(ionic.Platform.showStatusBar) { // they do not want it to be full screen StatusBar.show(); document.body.classList.remove('status-bar-hide'); } else { // it should be full screen StatusBar.hide(); document.body.classList.add('status-bar-hide'); } }); }, fullScreen: function(showFullScreen, showStatusBar) { // fullScreen( [showFullScreen[, showStatusBar] ] ) // showFullScreen: default is true if no param provided this.isFullScreen = (showFullScreen !== false); // add/remove the fullscreen classname to the body ionic.DomUtil.ready(function(){ // run this only when or if the DOM is ready if(ionic.Platform.isFullScreen) { document.body.classList.add('fullscreen'); } else { document.body.classList.remove('fullscreen'); } }); // showStatusBar: default is false if no param provided this.showStatusBar( (showStatusBar === true) ); } }; var platformName = null, // just the name, like iOS or Android platformVersion = null, // a float of the major and minor, like 7.1 readyCallbacks = []; // setup listeners to know when the device is ready to go function onWindowLoad() { if(ionic.Platform.isCordova()) { // the window and scripts are fully loaded, and a cordova/phonegap // object exists then let's listen for the deviceready document.addEventListener("deviceready", onPlatformReady, false); } else { // the window and scripts are fully loaded, but the window object doesn't have the // cordova/phonegap object, so its just a browser, not a webview wrapped w/ cordova onPlatformReady(); } window.removeEventListener("load", onWindowLoad, false); } window.addEventListener("load", onWindowLoad, false); function onPlatformReady() { // the device is all set to go, init our own stuff then fire off our event ionic.Platform.isReady = true; ionic.Platform.detect(); for(var x=0; x<readyCallbacks.length; x++) { // fire off all the callbacks that were added before the platform was ready readyCallbacks[x](); } readyCallbacks = []; ionic.trigger('platformready', { target: document }); document.removeEventListener("deviceready", onPlatformReady, false); } })(window.ionic); ; (function(window, document, ionic) { 'use strict'; // Ionic CSS polyfills ionic.CSS = {}; (function() { var keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform', '-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform']; for(var i = 0; i < keys.length; i++) { if(document.documentElement.style[keys[i]] !== undefined) { ionic.CSS.TRANSFORM = keys[i]; break; } } })(); // classList polyfill for them older Androids // https://gist.github.com/devongovett/1381839 if (!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') { Object.defineProperty(HTMLElement.prototype, 'classList', { get: function() { var self = this; function update(fn) { return function() { var x, classes = self.className.split(/\s+/); for(x=0; x<arguments.length; x++) { fn(classes, classes.indexOf(arguments[x]), arguments[x]); } self.className = classes.join(" "); }; } return { add: update(function(classes, index, value) { ~index || classes.push(value); }), remove: update(function(classes, index) { ~index && classes.splice(index, 1); }), toggle: update(function(classes, index, value) { ~index ? classes.splice(index, 1) : classes.push(value); }), contains: function(value) { return !!~self.className.split(/\s+/).indexOf(value); }, item: function(i) { return self.className.split(/\s+/)[i] || null; } }; } }); } // polyfill use to simulate native "tap" ionic.tapElement = function(target, e) { // simulate a normal click by running the element's click method then focus on it var ele = target.control || target; if(ele.disabled) return; var c = getCoordinates(e); // using initMouseEvent instead of MouseEvent for our Android friends var clickEvent = document.createEvent("MouseEvents"); clickEvent.initMouseEvent('click', true, true, window, 1, 0, 0, c.x, c.y, false, false, false, false, 0, null); ele.dispatchEvent(clickEvent); if(ele.tagName === 'INPUT' || ele.tagName === 'TEXTAREA' || ele.tagName === 'SELECT') { ele.focus(); e.preventDefault(); } else { blurActive(); } // remember the coordinates of this tap so if it happens again we can ignore it // but only if the coordinates are not already being actively disabled if( !isRecentTap(e) ) { recordCoordinates(e); } if(target.control) { return stopEvent(e); } }; function tapPolyfill(orgEvent) { // if the source event wasn't from a touch event then don't use this polyfill if(!orgEvent.gesture || !orgEvent.gesture.srcEvent) return; var e = orgEvent.gesture.srcEvent; // evaluate the actual source event, not the created event by gestures.js var ele = e.target; if( isRecentTap(e) ) { // if a tap in the same area just happened, don't continue return stopEvent(e); } while(ele) { // climb up the DOM looking to see if the tapped element is, or has a parent, of one of these if( ele.tagName === "INPUT" || ele.tagName === "A" || ele.tagName === "BUTTON" || ele.tagName === "LABEL" || ele.tagName === "TEXTAREA" || ele.tagName === "SELECT" ) { return ionic.tapElement(ele, e); } ele = ele.parentElement; } // they didn't tap one of the above elements // if the currently active element is an input, and they tapped outside // of the current input, then unset its focus (blur) so the keyboard goes away blurActive(); } function preventGhostClick(e) { if(e.target.control) { // this is a label that has an associated input // the native layer will send the actual event, so stop this one return stopEvent(e); } if( isRecentTap(e) ) { // a tap has already happened at these coordinates recently, ignore this event return stopEvent(e); } // remember the coordinates of this click so if a tap or click in the // same area quickly happened again we can ignore it recordCoordinates(e); } function isRecentTap(event) { // loop through the tap coordinates and see if the same area has been tapped recently var tapId, existingCoordinates, currentCoordinates; for(tapId in tapCoordinates) { existingCoordinates = tapCoordinates[tapId]; if(!currentCoordinates) currentCoordinates = getCoordinates(event); // lazy load it when needed if(currentCoordinates.x > existingCoordinates.x - HIT_RADIUS && currentCoordinates.x < existingCoordinates.x + HIT_RADIUS && currentCoordinates.y > existingCoordinates.y - HIT_RADIUS && currentCoordinates.y < existingCoordinates.y + HIT_RADIUS) { // the current tap coordinates are in the same area as a recent tap return existingCoordinates; } } } function recordCoordinates(event) { var c = getCoordinates(event); if(c.x && c.y) { var tapId = Date.now(); // only record tap coordinates if we have valid ones tapCoordinates[tapId] = { x: c.x, y: c.y, id: tapId }; setTimeout(function() { // delete the tap coordinates after X milliseconds, basically allowing // it so a tap can happen again in the same area in the future delete tapCoordinates[tapId]; }, CLICK_PREVENT_DURATION); } } function getCoordinates(event) { // This method can get coordinates for both a mouse click // or a touch depending on the given event var gesture = (event.gesture ? event.gesture : event); if(gesture) { var touches = gesture.touches && gesture.touches.length ? gesture.touches : [gesture]; var e = (gesture.changedTouches && gesture.changedTouches[0]) || (gesture.originalEvent && gesture.originalEvent.changedTouches && gesture.originalEvent.changedTouches[0]) || touches[0].originalEvent || touches[0]; if(e) return { x: e.clientX, y: e.clientY }; } return { x:0, y:0 }; } function removeClickPrevent(e) { setTimeout(function(){ var tap = isRecentTap(e); if(tap) delete tapCoordinates[tap.id]; }, REMOVE_PREVENT_DELAY); } function stopEvent(e){ e.stopPropagation(); e.preventDefault(); return false; } function blurActive() { var ele = document.activeElement; if(ele && (ele.tagName === "INPUT" || ele.tagName === "TEXTAREA" || ele.tagName === "SELECT")) { // using a timeout to prevent funky scrolling while a keyboard hides setTimeout(function(){ ele.blur(); }, 400); } } var tapCoordinates = {}; // used to remember coordinates to ignore if they happen again quickly var CLICK_PREVENT_DURATION = 1500; // max milliseconds ghostclicks in the same area should be prevented var REMOVE_PREVENT_DELAY = 375; // delay after a touchend/mouseup before removing the ghostclick prevent var HIT_RADIUS = 15; // set global click handler and check if the event should stop or not document.addEventListener('click', preventGhostClick, true); // global tap event listener polyfill for HTML elements that were "tapped" by the user ionic.on("tap", tapPolyfill, document); // listeners used to remove ghostclick prevention document.addEventListener('touchend', removeClickPrevent, false); document.addEventListener('mouseup', removeClickPrevent, false); })(this, document, ionic); ; (function(ionic) { /* for nextUid() function below */ var uid = ['0','0','0']; /** * Various utilities used throughout Ionic * * Some of these are adopted from underscore.js and backbone.js, both also MIT licensed. */ ionic.Utils = { arrayMove: function (arr, old_index, new_index) { if (new_index >= arr.length) { var k = new_index - arr.length; while ((k--) + 1) { arr.push(undefined); } } arr.splice(new_index, 0, arr.splice(old_index, 1)[0]); return arr; }, /** * Return a function that will be called with the given context */ proxy: function(func, context) { var args = Array.prototype.slice.call(arguments, 2); return function() { return func.apply(context, args.concat(Array.prototype.slice.call(arguments))); }; }, /** * Only call a function once in the given interval. * * @param func {Function} the function to call * @param wait {int} how long to wait before/after to allow function calls * @param immediate {boolean} whether to call immediately or after the wait interval */ debounce: function(func, wait, immediate) { var timeout, args, context, timestamp, result; return function() { context = this; args = arguments; timestamp = new Date(); var later = function() { var last = (new Date()) - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) result = func.apply(context, args); } }; var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) result = func.apply(context, args); return result; }; }, /** * Throttle the given fun, only allowing it to be * called at most every `wait` ms. */ throttle: function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : Date.now(); timeout = null; result = func.apply(context, args); }; return function() { var now = Date.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }, // Borrowed from Backbone.js's extend // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. inherit: function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && protoProps.hasOwnProperty('constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. ionic.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) ionic.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }, // Extend adapted from Underscore.js extend: function(obj) { var args = Array.prototype.slice.call(arguments, 1); for(var i = 0; i < args.length; i++) { var source = args[i]; if (source) { for (var prop in source) { obj[prop] = source[prop]; } } } return obj; }, /** * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ nextUid: function() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } }; // Bind a few of the most useful functions to the ionic scope ionic.inherit = ionic.Utils.inherit; ionic.extend = ionic.Utils.extend; ionic.throttle = ionic.Utils.throttle; ionic.proxy = ionic.Utils.proxy; ionic.debounce = ionic.Utils.debounce; })(window.ionic); ; (function(ionic) { ionic.Platform.ready(function() { if (ionic.Platform.is('android')) { androidKeyboardFix(); } }); function androidKeyboardFix() { var rememberedDeviceWidth = window.innerWidth; var rememberedDeviceHeight = window.innerHeight; var keyboardHeight; window.addEventListener('resize', resize); function resize() { //If the width of the window changes, we have an orientation change if (rememberedDeviceWidth !== window.innerWidth) { rememberedDeviceWidth = window.innerWidth; rememberedDeviceHeight = window.innerHeight; //If the height changes, and it's less than before, we have a keyboard open } else if (rememberedDeviceHeight !== window.innerHeight && window.innerHeight < rememberedDeviceHeight) { document.body.classList.add('hide-footer'); //Wait for next frame so document.activeElement is set ionic.requestAnimationFrame(handleKeyboardChange); } else { //Otherwise we have a keyboard close or a *really* weird resize document.body.classList.remove('hide-footer'); } function handleKeyboardChange() { //keyboard opens keyboardHeight = rememberedDeviceHeight - window.innerHeight; var activeEl = document.activeElement; if (activeEl) { //This event is caught by the nearest parent scrollView //of the activeElement ionic.trigger('scrollChildIntoView', { target: activeEl }, true); } } } } })(window.ionic); ; (function(ionic) { 'use strict'; ionic.views.View = function() { this.initialize.apply(this, arguments); }; ionic.views.View.inherit = ionic.inherit; ionic.extend(ionic.views.View.prototype, { initialize: function() {} }); })(window.ionic); ; var IS_INPUT_LIKE_REGEX = /input|textarea|select/i; /* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ /** * Generic animation class with support for dropped frames both optional easing and duration. * * Optional duration is useful when the lifetime is defined by another condition than time * e.g. speed of an animating object, etc. * * Dropped frame logic allows to keep using the same updater logic independent from the actual * rendering. This eases a lot of cases where it might be pretty complex to break down a state * based on the pure time difference. */ (function(global) { var time = Date.now || function() { return +new Date(); }; var desiredFrames = 60; var millisecondsPerSecond = 1000; var running = {}; var counter = 1; // Create namespaces if (!global.core) { global.core = { effect : {} }; } else if (!core.effect) { core.effect = {}; } core.effect.Animate = { /** * A requestAnimationFrame wrapper / polyfill. * * @param callback {Function} The callback to be invoked before the next repaint. * @param root {HTMLElement} The root element for the repaint */ requestAnimationFrame: (function() { // Check for request animation Frame support var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame; var isNative = !!requestFrame; if (requestFrame && !/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(requestFrame.toString())) { isNative = false; } if (isNative) { return function(callback, root) { requestFrame(callback, root) }; } var TARGET_FPS = 60; var requests = {}; var requestCount = 0; var rafHandle = 1; var intervalHandle = null; var lastActive = +new Date(); return function(callback, root) { var callbackHandle = rafHandle++; // Store callback requests[callbackHandle] = callback; requestCount++; // Create timeout at first request if (intervalHandle === null) { intervalHandle = setInterval(function() { var time = +new Date(); var currentRequests = requests; // Reset data structure before executing callbacks requests = {}; requestCount = 0; for(var key in currentRequests) { if (currentRequests.hasOwnProperty(key)) { currentRequests[key](time); lastActive = time; } } // Disable the timeout when nothing happens for a certain // period of time if (time - lastActive > 2500) { clearInterval(intervalHandle); intervalHandle = null; } }, 1000 / TARGET_FPS); } return callbackHandle; }; })(), /** * Stops the given animation. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation was stopped (aka, was running before) */ stop: function(id) { var cleared = running[id] != null; if (cleared) { running[id] = null; } return cleared; }, /** * Whether the given animation is still running. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation is still running */ isRunning: function(id) { return running[id] != null; }, /** * Start the animation. * * @param stepCallback {Function} Pointer to function which is executed on every step. * Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }` * @param verifyCallback {Function} Executed before every animation step. * Signature of the method should be `function() { return continueWithAnimation; }` * @param completedCallback {Function} * Signature of the method should be `function(droppedFrames, finishedAnimation) {}` * @param duration {Integer} Milliseconds to run the animation * @param easingMethod {Function} Pointer to easing function * Signature of the method should be `function(percent) { return modifiedValue; }` * @param root {Element} Render root, when available. Used for internal * usage of requestAnimationFrame. * @return {Integer} Identifier of animation. Can be used to stop it any time. */ start: function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) { var start = time(); var lastFrame = start; var percent = 0; var dropCounter = 0; var id = counter++; if (!root) { root = document.body; } // Compacting running db automatically every few new animations if (id % 20 === 0) { var newRunning = {}; for (var usedId in running) { newRunning[usedId] = true; } running = newRunning; } // This is the internal step method which is called every few milliseconds var step = function(virtual) { // Normalize virtual value var render = virtual !== true; // Get current time var now = time(); // Verification is executed before next animation step if (!running[id] || (verifyCallback && !verifyCallback(id))) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false); return; } // For the current rendering to apply let's update omitted steps in memory. // This is important to bring internal state variables up-to-date with progress in time. if (render) { var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1; for (var j = 0; j < Math.min(droppedFrames, 4); j++) { step(true); dropCounter++; } } // Compute percent value if (duration) { percent = (now - start) / duration; if (percent > 1) { percent = 1; } } // Execute step callback, then... var value = easingMethod ? easingMethod(percent) : percent; if ((stepCallback(value, now, render) === false || percent === 1) && render) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null); } else if (render) { lastFrame = now; core.effect.Animate.requestAnimationFrame(step, root); } }; // Mark as running running[id] = true; // Init first step core.effect.Animate.requestAnimationFrame(step, root); // Return unique animation ID return id; } }; })(this); /* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ var Scroller; (function(ionic) { var NOOP = function(){}; // Easing Equations (c) 2003 Robert Penner, all rights reserved. // Open source under the BSD License. /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeOutCubic = function(pos) { return (Math.pow((pos - 1), 3) + 1); }; /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeInOutCubic = function(pos) { if ((pos /= 0.5) < 1) { return 0.5 * Math.pow(pos, 3); } return 0.5 * (Math.pow((pos - 2), 3) + 2); }; /** * ionic.views.Scroll * A powerful scroll view with support for bouncing, pull to refresh, and paging. * @param {Object} options options for the scroll view * @class A scroll view system * @memberof ionic.views */ ionic.views.Scroll = ionic.views.View.inherit({ initialize: function(options) { var self = this; this.__container = options.el; this.__content = options.el.firstElementChild; //Remove any scrollTop attached to these elements; they are virtual scroll now //This also stops on-load-scroll-to-window.location.hash that the browser does setTimeout(function() { if (self.__container && self.__content) { self.__container.scrollTop = 0; self.__content.scrollTop = 0; } }); this.options = { /** Disable scrolling on x-axis by default */ scrollingX: false, scrollbarX: true, /** Enable scrolling on y-axis */ scrollingY: true, scrollbarY: true, startX: 0, startY: 0, /** The amount to dampen mousewheel events */ wheelDampen: 6, /** The minimum size the scrollbars scale to while scrolling */ minScrollbarSizeX: 5, minScrollbarSizeY: 5, /** Scrollbar fading after scrolling */ scrollbarsFade: true, scrollbarFadeDelay: 300, /** The initial fade delay when the pane is resized or initialized */ scrollbarResizeFadeDelay: 1000, /** Enable animations for deceleration, snap back, zooming and scrolling */ animating: true, /** duration for animations triggered by scrollTo/zoomTo */ animationDuration: 250, /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */ bouncing: true, /** Enable locking to the main axis if user moves only slightly on one of them at start */ locking: true, /** Enable pagination mode (switching between full page content panes) */ paging: false, /** Enable snapping of content to a configured pixel grid */ snapping: false, /** Enable zooming of content via API, fingers and mouse wheel */ zooming: false, /** Minimum zoom level */ minZoom: 0.5, /** Maximum zoom level */ maxZoom: 3, /** Multiply or decrease scrolling speed **/ speedMultiplier: 1, /** Callback that is fired on the later of touch end or deceleration end, provided that another scrolling action has not begun. Used to know when to fade out a scrollbar. */ scrollingComplete: NOOP, /** This configures the amount of change applied to deceleration when reaching boundaries **/ penetrationDeceleration : 0.03, /** This configures the amount of change applied to acceleration when reaching boundaries **/ penetrationAcceleration : 0.08, // The ms interval for triggering scroll events scrollEventInterval: 50 }; for (var key in options) { this.options[key] = options[key]; } this.hintResize = ionic.debounce(function() { self.resize(); }, 1000, true); this.triggerScrollEvent = ionic.throttle(function() { ionic.trigger('scroll', { scrollTop: self.__scrollTop, scrollLeft: self.__scrollLeft, target: self.__container }); }, this.options.scrollEventInterval); this.triggerScrollEndEvent = function() { ionic.trigger('scrollend', { scrollTop: self.__scrollTop, scrollLeft: self.__scrollLeft, target: self.__container }); }; this.__scrollLeft = this.options.startX; this.__scrollTop = this.options.startY; // Get the render update function, initialize event handlers, // and calculate the size of the scroll container this.__callback = this.getRenderFn(); this.__initEventHandlers(); this.__createScrollbars(); }, run: function() { this.resize(); // Fade them out this.__fadeScrollbars('out', this.options.scrollbarResizeFadeDelay); }, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: STATUS --------------------------------------------------------------------------- */ /** Whether only a single finger is used in touch handling */ __isSingleTouch: false, /** Whether a touch event sequence is in progress */ __isTracking: false, /** Whether a deceleration animation went to completion. */ __didDecelerationComplete: false, /** * Whether a gesture zoom/rotate event is in progress. Activates when * a gesturestart event happens. This has higher priority than dragging. */ __isGesturing: false, /** * Whether the user has moved by such a distance that we have enabled * dragging mode. Hint: It's only enabled after some pixels of movement to * not interrupt with clicks etc. */ __isDragging: false, /** * Not touching and dragging anymore, and smoothly animating the * touch sequence using deceleration. */ __isDecelerating: false, /** * Smoothly animating the currently configured change */ __isAnimating: false, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DIMENSIONS --------------------------------------------------------------------------- */ /** Available outer left position (from document perspective) */ __clientLeft: 0, /** Available outer top position (from document perspective) */ __clientTop: 0, /** Available outer width */ __clientWidth: 0, /** Available outer height */ __clientHeight: 0, /** Outer width of content */ __contentWidth: 0, /** Outer height of content */ __contentHeight: 0, /** Snapping width for content */ __snapWidth: 100, /** Snapping height for content */ __snapHeight: 100, /** Height to assign to refresh area */ __refreshHeight: null, /** Whether the refresh process is enabled when the event is released now */ __refreshActive: false, /** Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */ __refreshActivate: null, /** Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */ __refreshDeactivate: null, /** Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */ __refreshStart: null, /** Zoom level */ __zoomLevel: 1, /** Scroll position on x-axis */ __scrollLeft: 0, /** Scroll position on y-axis */ __scrollTop: 0, /** Maximum allowed scroll position on x-axis */ __maxScrollLeft: 0, /** Maximum allowed scroll position on y-axis */ __maxScrollTop: 0, /* Scheduled left position (final position when animating) */ __scheduledLeft: 0, /* Scheduled top position (final position when animating) */ __scheduledTop: 0, /* Scheduled zoom level (final scale when animating) */ __scheduledZoom: 0, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: LAST POSITIONS --------------------------------------------------------------------------- */ /** Left position of finger at start */ __lastTouchLeft: null, /** Top position of finger at start */ __lastTouchTop: null, /** Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */ __lastTouchMove: null, /** List of positions, uses three indexes for each state: left, top, timestamp */ __positions: null, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DECELERATION SUPPORT --------------------------------------------------------------------------- */ /** Minimum left scroll position during deceleration */ __minDecelerationScrollLeft: null, /** Minimum top scroll position during deceleration */ __minDecelerationScrollTop: null, /** Maximum left scroll position during deceleration */ __maxDecelerationScrollLeft: null, /** Maximum top scroll position during deceleration */ __maxDecelerationScrollTop: null, /** Current factor to modify horizontal scroll position with on every step */ __decelerationVelocityX: null, /** Current factor to modify vertical scroll position with on every step */ __decelerationVelocityY: null, /** the browser-specific property to use for transforms */ __transformProperty: null, __perspectiveProperty: null, /** scrollbar indicators */ __indicatorX: null, __indicatorY: null, /** Timeout for scrollbar fading */ __scrollbarFadeTimeout: null, /** whether we've tried to wait for size already */ __didWaitForSize: null, __sizerTimeout: null, __initEventHandlers: function() { var self = this; // Event Handler var container = this.__container; //Broadcasted when keyboard is shown on some platforms. //See js/utils/keyboard.js container.addEventListener('scrollChildIntoView', function(e) { var deviceHeight = window.innerHeight; var element = e.target; var elementHeight = e.target.offsetHeight; //getBoundingClientRect() will actually give us position relative to the viewport var elementDeviceTop = element.getBoundingClientRect().top; var elementScrollTop = ionic.DomUtil.getPositionInParent(element, container).top; //If the element is positioned under the keyboard... if (elementDeviceTop + elementHeight > deviceHeight) { //Put element in middle of visible screen self.scrollTo(0, elementScrollTop + elementHeight - (deviceHeight * 0.5), true); } //Only the first scrollView parent of the element that broadcasted this event //(the active element that needs to be shown) should receive this event e.stopPropagation(); }); function shouldIgnorePress(e) { // Don't react if initial down happens on a form element return e.target.tagName.match(IS_INPUT_LIKE_REGEX) || e.target.isContentEditable; } if ('ontouchstart' in window) { container.addEventListener("touchstart", function(e) { if (e.defaultPrevented || shouldIgnorePress(e)) { return; } self.doTouchStart(e.touches, e.timeStamp); e.preventDefault(); }, false); document.addEventListener("touchmove", function(e) { if(e.defaultPrevented) { return; } self.doTouchMove(e.touches, e.timeStamp); }, false); document.addEventListener("touchend", function(e) { self.doTouchEnd(e.timeStamp); }, false); } else { var mousedown = false; container.addEventListener("mousedown", function(e) { if (e.defaultPrevented || shouldIgnorePress(e)) { return; } self.doTouchStart([{ pageX: e.pageX, pageY: e.pageY }], e.timeStamp); e.preventDefault(); mousedown = true; }, false); document.addEventListener("mousemove", function(e) { if (!mousedown || e.defaultPrevented) { return; } self.doTouchMove([{ pageX: e.pageX, pageY: e.pageY }], e.timeStamp); mousedown = true; }, false); document.addEventListener("mouseup", function(e) { if (!mousedown) { return; } self.doTouchEnd(e.timeStamp); mousedown = false; }, false); document.addEventListener("mousewheel", function(e) { self.scrollBy(e.wheelDeltaX/self.options.wheelDampen, -e.wheelDeltaY/self.options.wheelDampen); }); } }, /** Create a scroll bar div with the given direction **/ __createScrollbar: function(direction) { var bar = document.createElement('div'), indicator = document.createElement('div'); indicator.className = 'scroll-bar-indicator'; if(direction == 'h') { bar.className = 'scroll-bar scroll-bar-h'; } else { bar.className = 'scroll-bar scroll-bar-v'; } bar.appendChild(indicator); return bar; }, __createScrollbars: function() { var indicatorX, indicatorY; if(this.options.scrollingX) { indicatorX = { el: this.__createScrollbar('h'), sizeRatio: 1 }; indicatorX.indicator = indicatorX.el.children[0]; if(this.options.scrollbarX) { this.__container.appendChild(indicatorX.el); } this.__indicatorX = indicatorX; } if(this.options.scrollingY) { indicatorY = { el: this.__createScrollbar('v'), sizeRatio: 1 }; indicatorY.indicator = indicatorY.el.children[0]; if(this.options.scrollbarY) { this.__container.appendChild(indicatorY.el); } this.__indicatorY = indicatorY; } }, __resizeScrollbars: function() { var self = this; // Bring the scrollbars in to show the content change self.__fadeScrollbars('in'); // Update horiz bar if(self.__indicatorX) { var width = Math.max(Math.round(self.__clientWidth * self.__clientWidth / (self.__contentWidth)), 20); if(width > self.__contentWidth) { width = 0; } self.__indicatorX.size = width; self.__indicatorX.minScale = this.options.minScrollbarSizeX / width; self.__indicatorX.indicator.style.width = width + 'px'; self.__indicatorX.maxPos = self.__clientWidth - width; self.__indicatorX.sizeRatio = self.__maxScrollLeft ? self.__indicatorX.maxPos / self.__maxScrollLeft : 1; } // Update vert bar if(self.__indicatorY) { var height = Math.max(Math.round(self.__clientHeight * self.__clientHeight / (self.__contentHeight)), 20); if(height > self.__contentHeight) { height = 0; } self.__indicatorY.size = height; self.__indicatorY.minScale = this.options.minScrollbarSizeY / height; self.__indicatorY.maxPos = self.__clientHeight - height; self.__indicatorY.indicator.style.height = height + 'px'; self.__indicatorY.sizeRatio = self.__maxScrollTop ? self.__indicatorY.maxPos / self.__maxScrollTop : 1; } }, /** * Move and scale the scrollbars as the page scrolls. */ __repositionScrollbars: function() { var self = this, width, heightScale, widthDiff, heightDiff, x, y, xstop = 0, ystop = 0; if(self.__indicatorX) { // Handle the X scrollbar // Don't go all the way to the right if we have a vertical scrollbar as well if(self.__indicatorY) xstop = 10; x = Math.round(self.__indicatorX.sizeRatio * self.__scrollLeft) || 0, // The the difference between the last content X position, and our overscrolled one widthDiff = self.__scrollLeft - (self.__maxScrollLeft - xstop); if(self.__scrollLeft < 0) { widthScale = Math.max(self.__indicatorX.minScale, (self.__indicatorX.size - Math.abs(self.__scrollLeft)) / self.__indicatorX.size); // Stay at left x = 0; // Make sure scale is transformed from the left/center origin point self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'left center'; } else if(widthDiff > 0) { widthScale = Math.max(self.__indicatorX.minScale, (self.__indicatorX.size - widthDiff) / self.__indicatorX.size); // Stay at the furthest x for the scrollable viewport x = self.__indicatorX.maxPos - xstop; // Make sure scale is transformed from the right/center origin point self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'right center'; } else { // Normal motion x = Math.min(self.__maxScrollLeft, Math.max(0, x)); widthScale = 1; } self.__indicatorX.indicator.style[self.__transformProperty] = 'translate3d(' + x + 'px, 0, 0) scaleX(' + widthScale + ')'; } if(self.__indicatorY) { y = Math.round(self.__indicatorY.sizeRatio * self.__scrollTop) || 0; // Don't go all the way to the right if we have a vertical scrollbar as well if(self.__indicatorX) ystop = 10; heightDiff = self.__scrollTop - (self.__maxScrollTop - ystop); if(self.__scrollTop < 0) { heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - Math.abs(self.__scrollTop)) / self.__indicatorY.size); // Stay at top y = 0; // Make sure scale is transformed from the center/top origin point self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center top'; } else if(heightDiff > 0) { heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - heightDiff) / self.__indicatorY.size); // Stay at bottom of scrollable viewport y = self.__indicatorY.maxPos - ystop; // Make sure scale is transformed from the center/bottom origin point self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center bottom'; } else { // Normal motion y = Math.min(self.__maxScrollTop, Math.max(0, y)); heightScale = 1; } self.__indicatorY.indicator.style[self.__transformProperty] = 'translate3d(0,' + y + 'px, 0) scaleY(' + heightScale + ')'; } }, __fadeScrollbars: function(direction, delay) { var self = this; if(!this.options.scrollbarsFade) { return; } var className = 'scroll-bar-fade-out'; if(self.options.scrollbarsFade === true) { clearTimeout(self.__scrollbarFadeTimeout); if(direction == 'in') { if(self.__indicatorX) { self.__indicatorX.indicator.classList.remove(className); } if(self.__indicatorY) { self.__indicatorY.indicator.classList.remove(className); } } else { self.__scrollbarFadeTimeout = setTimeout(function() { if(self.__indicatorX) { self.__indicatorX.indicator.classList.add(className); } if(self.__indicatorY) { self.__indicatorY.indicator.classList.add(className); } }, delay || self.options.scrollbarFadeDelay); } } }, __scrollingComplete: function() { var self = this; self.options.scrollingComplete(); self.__fadeScrollbars('out'); }, resize: function() { // Update Scroller dimensions for changed content // Add padding to bottom of content this.setDimensions( this.__container.clientWidth, this.__container.clientHeight, Math.max(this.__content.scrollWidth, this.__content.offsetWidth), Math.max(this.__content.scrollHeight, this.__content.offsetHeight) ); }, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ getRenderFn: function() { var self = this; var content = this.__content; var docStyle = document.documentElement.style; var engine; if ('MozAppearance' in docStyle) { engine = 'gecko'; } else if ('WebkitAppearance' in docStyle) { engine = 'webkit'; } else if (typeof navigator.cpuClass === 'string') { engine = 'trident'; } var vendorPrefix = { trident: 'ms', gecko: 'Moz', webkit: 'Webkit', presto: 'O' }[engine]; var helperElem = document.createElement("div"); var undef; var perspectiveProperty = vendorPrefix + "Perspective"; var transformProperty = vendorPrefix + "Transform"; var transformOriginProperty = vendorPrefix + 'TransformOrigin'; self.__perspectiveProperty = transformProperty; self.__transformProperty = transformProperty; self.__transformOriginProperty = transformOriginProperty; if (helperElem.style[perspectiveProperty] !== undef) { return function(left, top, zoom) { content.style[transformProperty] = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0)'; self.__repositionScrollbars(); self.triggerScrollEvent(); }; } else if (helperElem.style[transformProperty] !== undef) { return function(left, top, zoom) { content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px)'; self.__repositionScrollbars(); self.triggerScrollEvent(); }; } else { return function(left, top, zoom) { content.style.marginLeft = left ? (-left/zoom) + 'px' : ''; content.style.marginTop = top ? (-top/zoom) + 'px' : ''; content.style.zoom = zoom || ''; self.__repositionScrollbars(); self.triggerScrollEvent(); }; } }, /** * Configures the dimensions of the client (outer) and content (inner) elements. * Requires the available space for the outer element and the outer size of the inner element. * All values which are falsy (null or zero etc.) are ignored and the old value is kept. * * @param clientWidth {Integer} Inner width of outer element * @param clientHeight {Integer} Inner height of outer element * @param contentWidth {Integer} Outer width of inner element * @param contentHeight {Integer} Outer height of inner element */ setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) { var self = this; // Only update values which are defined if (clientWidth === +clientWidth) { self.__clientWidth = clientWidth; } if (clientHeight === +clientHeight) { self.__clientHeight = clientHeight; } if (contentWidth === +contentWidth) { self.__contentWidth = contentWidth; } if (contentHeight === +contentHeight) { self.__contentHeight = contentHeight; } // Refresh maximums self.__computeScrollMax(); self.__resizeScrollbars(); // Refresh scroll position self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Sets the client coordinates in relation to the document. * * @param left {Integer} Left position of outer element * @param top {Integer} Top position of outer element */ setPosition: function(left, top) { var self = this; self.__clientLeft = left || 0; self.__clientTop = top || 0; }, /** * Configures the snapping (when snapping is active) * * @param width {Integer} Snapping width * @param height {Integer} Snapping height */ setSnapSize: function(width, height) { var self = this; self.__snapWidth = width; self.__snapHeight = height; }, /** * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever * the user event is released during visibility of this zone. This was introduced by some apps on iOS like * the official Twitter client. * * @param height {Integer} Height of pull-to-refresh zone on top of rendered list * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release. * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled. * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh. */ activatePullToRefresh: function(height, activateCallback, deactivateCallback, startCallback) { var self = this; self.__refreshHeight = height; self.__refreshActivate = activateCallback; self.__refreshDeactivate = deactivateCallback; self.__refreshStart = startCallback; }, /** * Starts pull-to-refresh manually. */ triggerPullToRefresh: function() { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true); if (this.__refreshStart) { this.__refreshStart(); } }, /** * Signalizes that pull-to-refresh is finished. */ finishPullToRefresh: function() { var self = this; self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Returns the scroll position and zooming values * * @return {Map} `left` and `top` scroll position and `zoom` level */ getValues: function() { var self = this; return { left: self.__scrollLeft, top: self.__scrollTop, zoom: self.__zoomLevel }; }, /** * Returns the maximum scroll values * * @return {Map} `left` and `top` maximum scroll values */ getScrollMax: function() { var self = this; return { left: self.__maxScrollLeft, top: self.__maxScrollTop }; }, /** * Zooms to the given level. Supports optional animation. Zooms * the center when no coordinates are given. * * @param level {Number} Level to zoom to * @param animate {Boolean} Whether to use animation * @param originLeft {Number} Zoom in at given left coordinate * @param originTop {Number} Zoom in at given top coordinate */ zoomTo: function(level, animate, originLeft, originTop) { var self = this; if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } var oldLevel = self.__zoomLevel; // Normalize input origin to center of viewport if not defined if (originLeft == null) { originLeft = self.__clientWidth / 2; } if (originTop == null) { originTop = self.__clientHeight / 2; } // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(level); // Recompute left and top coordinates based on new zoom level var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft; var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop; // Limit x-axis if (left > self.__maxScrollLeft) { left = self.__maxScrollLeft; } else if (left < 0) { left = 0; } // Limit y-axis if (top > self.__maxScrollTop) { top = self.__maxScrollTop; } else if (top < 0) { top = 0; } // Push values out self.__publish(left, top, level, animate); }, /** * Zooms the content by the given factor. * * @param factor {Number} Zoom by given factor * @param animate {Boolean} Whether to use animation * @param originLeft {Number} Zoom in at given left coordinate * @param originTop {Number} Zoom in at given top coordinate */ zoomBy: function(factor, animate, originLeft, originTop) { var self = this; self.zoomTo(self.__zoomLevel * factor, animate, originLeft, originTop); }, /** * Scrolls to the given position. Respect limitations and snapping automatically. * * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code> * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code> * @param animate {Boolean} Whether the scrolling should happen using an animation * @param zoom {Number} Zoom level to go to */ scrollTo: function(left, top, animate, zoom) { var self = this; // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } // Correct coordinates based on new zoom level if (zoom != null && zoom !== self.__zoomLevel) { if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } left *= zoom; top *= zoom; // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(zoom); } else { // Keep zoom when not defined zoom = self.__zoomLevel; } if (!self.options.scrollingX) { left = self.__scrollLeft; } else { if (self.options.paging) { left = Math.round(left / self.__clientWidth) * self.__clientWidth; } else if (self.options.snapping) { left = Math.round(left / self.__snapWidth) * self.__snapWidth; } } if (!self.options.scrollingY) { top = self.__scrollTop; } else { if (self.options.paging) { top = Math.round(top / self.__clientHeight) * self.__clientHeight; } else if (self.options.snapping) { top = Math.round(top / self.__snapHeight) * self.__snapHeight; } } // Limit for allowed ranges left = Math.max(Math.min(self.__maxScrollLeft, left), 0); top = Math.max(Math.min(self.__maxScrollTop, top), 0); // Don't animate when no change detected, still call publish to make sure // that rendered position is really in-sync with internal data if (left === self.__scrollLeft && top === self.__scrollTop) { animate = false; } // Publish new values self.__publish(left, top, zoom, animate); }, /** * Scroll by the given offset * * @param left {Number} Scroll x-axis by given offset * @param top {Number} Scroll x-axis by given offset * @param animate {Boolean} Whether to animate the given change */ scrollBy: function(left, top, animate) { var self = this; var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft; var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop; self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate); }, /* --------------------------------------------------------------------------- EVENT CALLBACKS --------------------------------------------------------------------------- */ /** * Mouse wheel handler for zooming support */ doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) { var self = this; var change = wheelDelta > 0 ? 0.97 : 1.03; return self.zoomTo(self.__zoomLevel * change, false, pageX - self.__clientLeft, pageY - self.__clientTop); }, /** * Touch start handler for scrolling support */ doTouchStart: function(touches, timeStamp) { this.hintResize(); // Array-like check is enough here if (touches.length == null) { throw new Error("Invalid touch list: " + touches); } if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; self.__fadeScrollbars('in'); // Reset interruptedAnimation flag self.__interruptedAnimation = true; // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; self.__interruptedAnimation = true; } // Stop animation if (self.__isAnimating) { core.effect.Animate.stop(self.__isAnimating); self.__isAnimating = false; self.__interruptedAnimation = true; } // Use center point when dealing with two fingers var currentTouchLeft, currentTouchTop; var isSingleTouch = touches.length === 1; if (isSingleTouch) { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } else { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } // Store initial positions self.__initialTouchLeft = currentTouchLeft; self.__initialTouchTop = currentTouchTop; // Store current zoom level self.__zoomLevelStart = self.__zoomLevel; // Store initial touch positions self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; // Store initial move time stamp self.__lastTouchMove = timeStamp; // Reset initial scale self.__lastScale = 1; // Reset locking flags self.__enableScrollX = !isSingleTouch && self.options.scrollingX; self.__enableScrollY = !isSingleTouch && self.options.scrollingY; // Reset tracking flag self.__isTracking = true; // Reset deceleration complete flag self.__didDecelerationComplete = false; // Dragging starts directly with two fingers, otherwise lazy with an offset self.__isDragging = !isSingleTouch; // Some features are disabled in multi touch scenarios self.__isSingleTouch = isSingleTouch; // Clearing data structure self.__positions = []; }, /** * Touch move handler for scrolling support */ doTouchMove: function(touches, timeStamp, scale) { // Array-like check is enough here if (touches.length == null) { throw new Error("Invalid touch list: " + touches); } if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Ignore event when tracking is not enabled (event might be outside of element) if (!self.__isTracking) { return; } var currentTouchLeft, currentTouchTop; // Compute move based around of center of fingers if (touches.length === 2) { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } else { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } var positions = self.__positions; // Are we already is dragging mode? if (self.__isDragging) { // Compute move distance var moveX = currentTouchLeft - self.__lastTouchLeft; var moveY = currentTouchTop - self.__lastTouchTop; // Read previous scroll position and zooming var scrollLeft = self.__scrollLeft; var scrollTop = self.__scrollTop; var level = self.__zoomLevel; // Work with scaling if (scale != null && self.options.zooming) { var oldLevel = level; // Recompute level based on previous scale and new scale level = level / self.__lastScale * scale; // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Only do further compution when change happened if (oldLevel !== level) { // Compute relative event position to container var currentTouchLeftRel = currentTouchLeft - self.__clientLeft; var currentTouchTopRel = currentTouchTop - self.__clientTop; // Recompute left and top coordinates based on new zoom level scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel; scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel; // Recompute max scroll values self.__computeScrollMax(level); } } if (self.__enableScrollX) { scrollLeft -= moveX * this.options.speedMultiplier; var maxScrollLeft = self.__maxScrollLeft; if (scrollLeft > maxScrollLeft || scrollLeft < 0) { // Slow down on the edges if (self.options.bouncing) { scrollLeft += (moveX / 2 * this.options.speedMultiplier); } else if (scrollLeft > maxScrollLeft) { scrollLeft = maxScrollLeft; } else { scrollLeft = 0; } } } // Compute new vertical scroll position if (self.__enableScrollY) { scrollTop -= moveY * this.options.speedMultiplier; var maxScrollTop = self.__maxScrollTop; if (scrollTop > maxScrollTop || scrollTop < 0) { // Slow down on the edges if (self.options.bouncing || (self.__refreshHeight && scrollTop < 0)) { scrollTop += (moveY / 2 * this.options.speedMultiplier); // Support pull-to-refresh (only when only y is scrollable) if (!self.__enableScrollX && self.__refreshHeight != null) { if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) { self.__refreshActive = true; if (self.__refreshActivate) { self.__refreshActivate(); } } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } else if (scrollTop > maxScrollTop) { scrollTop = maxScrollTop; } else { scrollTop = 0; } } } // Keep list from growing infinitely (holding min 10, max 20 measure points) if (positions.length > 60) { positions.splice(0, 30); } // Track scroll movement for decleration positions.push(scrollLeft, scrollTop, timeStamp); // Sync scroll position self.__publish(scrollLeft, scrollTop, level); // Otherwise figure out whether we are switching into dragging mode now. } else { var minimumTrackingForScroll = self.options.locking ? 3 : 0; var minimumTrackingForDrag = 5; var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft); var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop); self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll; self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll; positions.push(self.__scrollLeft, self.__scrollTop, timeStamp); self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag); if (self.__isDragging) { self.__interruptedAnimation = false; } } // Update last touch positions and time stamp for next event self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; self.__lastTouchMove = timeStamp; self.__lastScale = scale; }, /** * Touch end handler for scrolling support */ doTouchEnd: function(timeStamp) { if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Ignore event when tracking is not enabled (no touchstart event on element) // This is required as this listener ('touchmove') sits on the document and not on the element itself. if (!self.__isTracking) { return; } // Not touching anymore (when two finger hit the screen there are two touch end events) self.__isTracking = false; // Be sure to reset the dragging flag now. Here we also detect whether // the finger has moved fast enough to switch into a deceleration animation. if (self.__isDragging) { // Reset dragging flag self.__isDragging = false; // Start deceleration // Verify that the last move detected was in some relevant time frame if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) { // Then figure out what the scroll position was about 100ms ago var positions = self.__positions; var endPos = positions.length - 1; var startPos = endPos; // Move pointer to position measured 100ms ago for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) { startPos = i; } // If start and stop position is identical in a 100ms timeframe, // we cannot compute any useful deceleration. if (startPos !== endPos) { // Compute relative movement between these two points var timeOffset = positions[endPos] - positions[startPos]; var movedLeft = self.__scrollLeft - positions[startPos - 2]; var movedTop = self.__scrollTop - positions[startPos - 1]; // Based on 50ms compute the movement to apply for each render step self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60); self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60); // How much velocity is required to start the deceleration var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? 4 : 1; // Verify that we have enough velocity to start deceleration if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) { // Deactivate pull-to-refresh when decelerating if (!self.__refreshActive) { self.__startDeceleration(timeStamp); } } } else { self.__scrollingComplete(); } } else if ((timeStamp - self.__lastTouchMove) > 100) { self.__scrollingComplete(); } } // If this was a slower move it is per default non decelerated, but this // still means that we want snap back to the bounds which is done here. // This is placed outside the condition above to improve edge case stability // e.g. touchend fired without enabled dragging. This should normally do not // have modified the scroll positions or even showed the scrollbars though. if (!self.__isDecelerating) { if (self.__refreshActive && self.__refreshStart) { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true); if (self.__refreshStart) { self.__refreshStart(); } } else { if (self.__interruptedAnimation || self.__isDragging) { self.__scrollingComplete(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel); // Directly signalize deactivation (nothing todo on refresh?) if (self.__refreshActive) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } // Fully cleanup list self.__positions.length = 0; }, /* --------------------------------------------------------------------------- PRIVATE API --------------------------------------------------------------------------- */ /** * Applies the scroll position to the content element * * @param left {Number} Left scroll position * @param top {Number} Top scroll position * @param animate {Boolean} Whether animation should be used to move to the new coordinates */ __publish: function(left, top, zoom, animate) { var self = this; // Remember whether we had an animation, then we try to continue based on the current "drive" of the animation var wasAnimating = self.__isAnimating; if (wasAnimating) { core.effect.Animate.stop(wasAnimating); self.__isAnimating = false; } if (animate && self.options.animating) { // Keep scheduled positions for scrollBy/zoomBy functionality self.__scheduledLeft = left; self.__scheduledTop = top; self.__scheduledZoom = zoom; var oldLeft = self.__scrollLeft; var oldTop = self.__scrollTop; var oldZoom = self.__zoomLevel; var diffLeft = left - oldLeft; var diffTop = top - oldTop; var diffZoom = zoom - oldZoom; var step = function(percent, now, render) { if (render) { self.__scrollLeft = oldLeft + (diffLeft * percent); self.__scrollTop = oldTop + (diffTop * percent); self.__zoomLevel = oldZoom + (diffZoom * percent); // Push values out if (self.__callback) { self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel); } } }; var verify = function(id) { return self.__isAnimating === id; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { if (animationId === self.__isAnimating) { self.__isAnimating = false; } if (self.__didDecelerationComplete || wasFinished) { self.__scrollingComplete(); } if (self.options.zooming) { self.__computeScrollMax(); } }; // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out self.__isAnimating = core.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic); } else { self.__scheduledLeft = self.__scrollLeft = left; self.__scheduledTop = self.__scrollTop = top; self.__scheduledZoom = self.__zoomLevel = zoom; // Push values out if (self.__callback) { self.__callback(left, top, zoom); } // Fix max scroll ranges if (self.options.zooming) { self.__computeScrollMax(); } } }, /** * Recomputes scroll minimum values based on client dimensions and content dimensions. */ __computeScrollMax: function(zoomLevel) { var self = this; if (zoomLevel == null) { zoomLevel = self.__zoomLevel; } self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0); self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0); if(!self.__didWaitForSize && self.__maxScrollLeft == 0 && self.__maxScrollTop == 0) { self.__didWaitForSize = true; self.__waitForSize(); } }, /** * If the scroll view isn't sized correctly on start, wait until we have at least some size */ __waitForSize: function() { var self = this; clearTimeout(self.__sizerTimeout); var sizer = function() { self.resize(); if((self.options.scrollingX && self.__maxScrollLeft == 0) || (self.options.scrollingY && self.__maxScrollTop == 0)) { //self.__sizerTimeout = setTimeout(sizer, 1000); } }; sizer(); self.__sizerTimeout = setTimeout(sizer, 1000); }, /* --------------------------------------------------------------------------- ANIMATION (DECELERATION) SUPPORT --------------------------------------------------------------------------- */ /** * Called when a touch sequence end and the speed of the finger was high enough * to switch into deceleration mode. */ __startDeceleration: function(timeStamp) { var self = this; if (self.options.paging) { var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0); var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0); var clientWidth = self.__clientWidth; var clientHeight = self.__clientHeight; // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area. // Each page should have exactly the size of the client area. self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth; self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight; self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth; self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight; } else { self.__minDecelerationScrollLeft = 0; self.__minDecelerationScrollTop = 0; self.__maxDecelerationScrollLeft = self.__maxScrollLeft; self.__maxDecelerationScrollTop = self.__maxScrollTop; } // Wrap class method var step = function(percent, now, render) { self.__stepThroughDeceleration(render); }; // How much velocity is required to keep the deceleration running self.__minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1; // Detect whether it's still worth to continue animating steps // If we are already slow enough to not being user perceivable anymore, we stop the whole process here. var verify = function() { var shouldContinue = Math.abs(self.__decelerationVelocityX) >= self.__minVelocityToKeepDecelerating || Math.abs(self.__decelerationVelocityY) >= self.__minVelocityToKeepDecelerating; if (!shouldContinue) { self.__didDecelerationComplete = true; } return shouldContinue; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { self.__isDecelerating = false; if (self.__didDecelerationComplete) { self.__scrollingComplete(); } // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions if(self.options.paging) { self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping); } }; // Start animation and switch on flag self.__isDecelerating = core.effect.Animate.start(step, verify, completed); }, /** * Called on every step of the animation * * @param inMemory {Boolean} Whether to not render the current step, but keep it in memory only. Used internally only! */ __stepThroughDeceleration: function(render) { var self = this; // // COMPUTE NEXT SCROLL POSITION // // Add deceleration to scroll position var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX; var scrollTop = self.__scrollTop + self.__decelerationVelocityY; // // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE // if (!self.options.bouncing) { var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft); if (scrollLeftFixed !== scrollLeft) { scrollLeft = scrollLeftFixed; self.__decelerationVelocityX = 0; } var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop); if (scrollTopFixed !== scrollTop) { scrollTop = scrollTopFixed; self.__decelerationVelocityY = 0; } } // // UPDATE SCROLL POSITION // if (render) { self.__publish(scrollLeft, scrollTop, self.__zoomLevel); } else { self.__scrollLeft = scrollLeft; self.__scrollTop = scrollTop; } // // SLOW DOWN // // Slow down velocity on every iteration if (!self.options.paging) { // This is the factor applied to every iteration of the animation // to slow down the process. This should emulate natural behavior where // objects slow down when the initiator of the movement is removed var frictionFactor = 0.95; self.__decelerationVelocityX *= frictionFactor; self.__decelerationVelocityY *= frictionFactor; } // // BOUNCING SUPPORT // if (self.options.bouncing) { var scrollOutsideX = 0; var scrollOutsideY = 0; // This configures the amount of change applied to deceleration/acceleration when reaching boundaries var penetrationDeceleration = self.options.penetrationDeceleration; var penetrationAcceleration = self.options.penetrationAcceleration; // Check limits if (scrollLeft < self.__minDecelerationScrollLeft) { scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft; } else if (scrollLeft > self.__maxDecelerationScrollLeft) { scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft; } if (scrollTop < self.__minDecelerationScrollTop) { scrollOutsideY = self.__minDecelerationScrollTop - scrollTop; } else if (scrollTop > self.__maxDecelerationScrollTop) { scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop; } // Slow down until slow enough, then flip back to snap position if (scrollOutsideX !== 0) { var isHeadingOutwardsX = scrollOutsideX * self.__decelerationVelocityX <= self.__minDecelerationScrollLeft; if (isHeadingOutwardsX) { self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration; } var isStoppedX = Math.abs(self.__decelerationVelocityX) <= self.__minVelocityToKeepDecelerating; //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds if (!isHeadingOutwardsX || isStoppedX) { self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration; } } if (scrollOutsideY !== 0) { var isHeadingOutwardsY = scrollOutsideY * self.__decelerationVelocityY <= self.__minDecelerationScrollTop; if (isHeadingOutwardsY) { self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration; } var isStoppedY = Math.abs(self.__decelerationVelocityY) <= self.__minVelocityToKeepDecelerating; //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds if (!isHeadingOutwardsY || isStoppedY) { self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration; } } } } }); })(ionic); ; (function(ionic) { 'use strict'; /** * An ActionSheet is the slide up menu popularized on iOS. * * You see it all over iOS apps, where it offers a set of options * triggered after an action. */ ionic.views.ActionSheet = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; }, show: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.add('active'); }, hide: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.remove('active'); } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.HeaderBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; ionic.extend(this, { alignTitle: 'center' }, opts); this.align(); }, /** * Align the title text given the buttons in the header * so that the header text size is maximized and aligned * correctly as long as possible. */ align: ionic.animationFrameThrottle(function(titleSelector) { // Find the titleEl element var titleEl = this.el.querySelector(titleSelector || '.title'); if(!titleEl) { return; } var i, c, childSize; var childNodes = this.el.childNodes; var leftWidth = 0; var rightWidth = 0; var isCountingRightWidth = true; // Compute how wide the left children are // Skip all titles (there may still be two titles, one leaving the dom) // Once we encounter a titleEl, realize we are now counting the right-buttons, not left for(i = 0; i < childNodes.length; i++) { c = childNodes[i]; if (c.tagName && c.tagName.toLowerCase() == 'h1') { isCountingRightWidth = false; continue; } childSize = null; if(c.nodeType == 3) { childSize = ionic.DomUtil.getTextBounds(c); } else if(c.nodeType == 1) { childSize = c.getBoundingClientRect(); } if(childSize) { if (isCountingRightWidth) { rightWidth += childSize.width; } else { leftWidth += childSize.width; } } } var margin = Math.max(leftWidth, rightWidth) + 10; // Size and align the header titleEl based on the sizes of the left and // right children, and the desired alignment mode if(this.alignTitle == 'center') { if(margin > 10) { titleEl.style.left = margin + 'px'; titleEl.style.right = margin + 'px'; } if(titleEl.offsetWidth < titleEl.scrollWidth) { if(rightWidth > 0) { titleEl.style.right = (rightWidth + 5) + 'px'; } } } else if(this.alignTitle == 'left') { titleEl.classList.add('titleEl-left'); if(leftWidth > 0) { titleEl.style.left = (leftWidth + 15) + 'px'; } } else if(this.alignTitle == 'right') { titleEl.classList.add('titleEl-right'); if(rightWidth > 0) { titleEl.style.right = (rightWidth + 15) + 'px'; } } }) }); })(ionic); ; (function(ionic) { 'use strict'; var ITEM_CLASS = 'item'; var ITEM_CONTENT_CLASS = 'item-content'; var ITEM_SLIDING_CLASS = 'item-sliding'; var ITEM_OPTIONS_CLASS = 'item-options'; var ITEM_PLACEHOLDER_CLASS = 'item-placeholder'; var ITEM_REORDERING_CLASS = 'item-reordering'; var ITEM_DRAG_CLASS = 'item-drag'; var DragOp = function() {}; DragOp.prototype = { start: function(e) { }, drag: function(e) { }, end: function(e) { } }; var SlideDrag = function(opts) { this.dragThresholdX = opts.dragThresholdX || 10; this.el = opts.el; }; SlideDrag.prototype = new DragOp(); SlideDrag.prototype.start = function(e) { var content, buttons, offsetX, buttonsWidth; if(e.target.classList.contains(ITEM_CONTENT_CLASS)) { content = e.target; } else if(e.target.classList.contains(ITEM_CLASS)) { content = e.target.querySelector('.' + ITEM_CONTENT_CLASS); } // If we don't have a content area as one of our children (or ourselves), skip if(!content) { return; } // Make sure we aren't animating as we slide content.classList.remove(ITEM_SLIDING_CLASS); // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start) offsetX = parseFloat(content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0; // Grab the buttons buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS); if(!buttons) { return; } buttonsWidth = buttons.offsetWidth; this._currentDrag = { buttonsWidth: buttonsWidth, content: content, startOffsetX: offsetX }; }; SlideDrag.prototype.drag = ionic.animationFrameThrottle(function(e) { var buttonsWidth; // We really aren't dragging if(!this._currentDrag) { return; } // Check if we should start dragging. Check if we've dragged past the threshold, // or we are starting from the open state. if(!this._isDragging && ((Math.abs(e.gesture.deltaX) > this.dragThresholdX) || (Math.abs(this._currentDrag.startOffsetX) > 0))) { this._isDragging = true; } if(this._isDragging) { buttonsWidth = this._currentDrag.buttonsWidth; // Grab the new X point, capping it at zero var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX); // If the new X position is past the buttons, we need to slow down the drag (rubber band style) if(newX < -buttonsWidth) { // Calculate the new X position, capped at the top of the buttons newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4))); } this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + newX + 'px, 0, 0)'; this._currentDrag.content.style.webkitTransition = 'none'; } }); SlideDrag.prototype.end = function(e, doneCallback) { var _this = this; // There is no drag, just end immediately if(!this._currentDrag) { doneCallback && doneCallback(); return; } // If we are currently dragging, we want to snap back into place // The final resting point X will be the width of the exposed buttons var restingPoint = -this._currentDrag.buttonsWidth; // Check if the drag didn't clear the buttons mid-point // and we aren't moving fast enough to swipe open if(e.gesture.deltaX > -(this._currentDrag.buttonsWidth/2)) { // If we are going left but too slow, or going right, go back to resting if(e.gesture.direction == "left" && Math.abs(e.gesture.velocityX) < 0.3) { restingPoint = 0; } else if(e.gesture.direction == "right") { restingPoint = 0; } } // var content = this._currentDrag.content; // var onRestingAnimationEnd = function(e) { // if(e.propertyName == '-webkit-transform') { // if(content) content.classList.remove(ITEM_SLIDING_CLASS); // } // e.target.removeEventListener('webkitTransitionEnd', onRestingAnimationEnd); // }; ionic.requestAnimationFrame(function() { // var currentX = parseFloat(_this._currentDrag.content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0; // if(currentX !== restingPoint) { // _this._currentDrag.content.classList.add(ITEM_SLIDING_CLASS); // _this._currentDrag.content.addEventListener('webkitTransitionEnd', onRestingAnimationEnd); // } if(restingPoint === 0) { _this._currentDrag.content.style[ionic.CSS.TRANSFORM] = ''; } else { _this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + restingPoint + 'px, 0, 0)'; } _this._currentDrag.content.style[ionic.CSS.TRANSFORM] = ''; // Kill the current drag _this._currentDrag = null; // We are done, notify caller doneCallback && doneCallback(); }); }; var ReorderDrag = function(opts) { this.dragThresholdY = opts.dragThresholdY || 0; this.onReorder = opts.onReorder; this.el = opts.el; this.scrollEl = opts.scrollEl; this.scrollView = opts.scrollView; }; ReorderDrag.prototype = new DragOp(); ReorderDrag.prototype._moveElement = function(e) { var y = (e.gesture.center.pageY - this._currentDrag.elementHeight/2); this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(0, '+y+'px, 0)'; }; ReorderDrag.prototype.start = function(e) { var content; // Grab the starting Y point for the item var offsetY = this.el.offsetTop;//parseFloat(this.el.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[1]) || 0; var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase()); var elementHeight = this.el.offsetHeight; var placeholder = this.el.cloneNode(true); // If we have a scroll pane, move our draggable element outside of it // We do this because when we drag our element down below the edge of the page // and scroll the scroll-pane, if the element is *part* of the scroll-pane, // it will scroll 'with' the scroll-pane's contents and change position. var appendToElement = (this.scrollEl || this.el).parentNode; placeholder.classList.add(ITEM_PLACEHOLDER_CLASS); this.el.parentNode.insertBefore(placeholder, this.el); this.el.classList.add(ITEM_REORDERING_CLASS); appendToElement.parentNode.appendChild(this.el); this._currentDrag = { elementHeight: elementHeight, startIndex: startIndex, placeholder: placeholder, scrollHeight: scroll, list: placeholder.parentNode }; this._moveElement(e); }; ReorderDrag.prototype.drag = ionic.animationFrameThrottle(function(e) { // We really aren't dragging if(!this._currentDrag) { return; } var scrollY = 0; var pageY = e.gesture.center.pageY; //If we have a scrollView, check scroll boundaries for dragged element and scroll if necessary if (this.scrollView) { var container = this.scrollEl; scrollY = this.scrollView.getValues().top; var containerTop = container.offsetTop; var pixelsPastTop = containerTop - pageY + this._currentDrag.elementHeight/2; var pixelsPastBottom = pageY + this._currentDrag.elementHeight/2 - containerTop - container.offsetHeight; if (e.gesture.deltaY < 0 && pixelsPastTop > 0 && scrollY > 0) { this.scrollView.scrollBy(null, -pixelsPastTop); } if (e.gesture.deltaY > 0 && pixelsPastBottom > 0) { if (scrollY < this.scrollView.getScrollMax().top) { this.scrollView.scrollBy(null, pixelsPastBottom); } } } // Check if we should start dragging. Check if we've dragged past the threshold, // or we are starting from the open state. if(!this._isDragging && Math.abs(e.gesture.deltaY) > this.dragThresholdY) { this._isDragging = true; } if(this._isDragging) { this._moveElement(e); this._currentDrag.currentY = scrollY + pageY - this._currentDrag.placeholder.parentNode.offsetTop; this._reorderItems(); } }); // When an item is dragged, we need to reorder any items for sorting purposes ReorderDrag.prototype._reorderItems = function() { var placeholder = this._currentDrag.placeholder; var siblings = Array.prototype.slice.call(this._currentDrag.placeholder.parentNode.children); var index = siblings.indexOf(this._currentDrag.placeholder); var topSibling = siblings[Math.max(0, index - 1)]; var bottomSibling = siblings[Math.min(siblings.length, index+1)]; var thisOffsetTop = this._currentDrag.currentY;// + this._currentDrag.startOffsetTop; if(topSibling && (thisOffsetTop < topSibling.offsetTop + topSibling.offsetHeight/2)) { ionic.DomUtil.swapNodes(this._currentDrag.placeholder, topSibling); return index - 1; } else if(bottomSibling && thisOffsetTop > (bottomSibling.offsetTop + bottomSibling.offsetHeight/2)) { ionic.DomUtil.swapNodes(bottomSibling, this._currentDrag.placeholder); return index + 1; } }; ReorderDrag.prototype.end = function(e, doneCallback) { if(!this._currentDrag) { doneCallback && doneCallback(); return; } var placeholder = this._currentDrag.placeholder; var finalPosition = ionic.DomUtil.getChildIndex(placeholder, placeholder.nodeName.toLowerCase()); // Reposition the element this.el.classList.remove(ITEM_REORDERING_CLASS); this.el.style[ionic.CSS.TRANSFORM] = ''; placeholder.parentNode.insertBefore(this.el, placeholder); placeholder.parentNode.removeChild(placeholder); this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalPosition); this._currentDrag = null; doneCallback && doneCallback(); }; /** * The ListView handles a list of items. It will process drag animations, edit mode, * and other operations that are common on mobile lists or table views. */ ionic.views.ListView = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; opts = ionic.extend({ onReorder: function(el, oldIndex, newIndex) {}, virtualRemoveThreshold: -200, virtualAddThreshold: 200 }, opts); ionic.extend(this, opts); if(!this.itemHeight && this.listEl) { this.itemHeight = this.listEl.children[0] && parseInt(this.listEl.children[0].style.height, 10); } //ionic.views.ListView.__super__.initialize.call(this, opts); this.onRefresh = opts.onRefresh || function() {}; this.onRefreshOpening = opts.onRefreshOpening || function() {}; this.onRefreshHolding = opts.onRefreshHolding || function() {}; window.ionic.onGesture('touch', function(e) { _this._handleTouch(e); }, this.el); window.ionic.onGesture('release', function(e) { _this._handleEndDrag(e); }, this.el); window.ionic.onGesture('drag', function(e) { _this._handleDrag(e); }, this.el); // Start the drag states this._initDrag(); }, /** * Called to tell the list to stop refreshing. This is useful * if you are refreshing the list and are done with refreshing. */ stopRefreshing: function() { var refresher = this.el.querySelector('.list-refresher'); refresher.style.height = '0px'; }, /** * If we scrolled and have virtual mode enabled, compute the window * of active elements in order to figure out the viewport to render. */ didScroll: function(e) { if(this.isVirtual) { var itemHeight = this.itemHeight; // TODO: This would be inaccurate if we are windowed var totalItems = this.listEl.children.length; // Grab the total height of the list var scrollHeight = e.target.scrollHeight; // Get the viewport height var viewportHeight = this.el.parentNode.offsetHeight; // scrollTop is the current scroll position var scrollTop = e.scrollTop; // High water is the pixel position of the first element to include (everything before // that will be removed) var highWater = Math.max(0, e.scrollTop + this.virtualRemoveThreshold); // Low water is the pixel position of the last element to include (everything after // that will be removed) var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + this.virtualAddThreshold); // Compute how many items per viewport size can show var itemsPerViewport = Math.floor((lowWater - highWater) / itemHeight); // Get the first and last elements in the list based on how many can fit // between the pixel range of lowWater and highWater var first = parseInt(Math.abs(highWater / itemHeight), 10); var last = parseInt(Math.abs(lowWater / itemHeight), 10); // Get the items we need to remove this._virtualItemsToRemove = Array.prototype.slice.call(this.listEl.children, 0, first); // Grab the nodes we will be showing var nodes = Array.prototype.slice.call(this.listEl.children, first, first + itemsPerViewport); this.renderViewport && this.renderViewport(highWater, lowWater, first, last); } }, didStopScrolling: function(e) { if(this.isVirtual) { for(var i = 0; i < this._virtualItemsToRemove.length; i++) { var el = this._virtualItemsToRemove[i]; //el.parentNode.removeChild(el); this.didHideItem && this.didHideItem(i); } // Once scrolling stops, check if we need to remove old items } }, _initDrag: function() { //ionic.views.ListView.__super__._initDrag.call(this); //this._isDragging = false; this._dragOp = null; }, // Return the list item from the given target _getItem: function(target) { while(target) { if(target.classList.contains(ITEM_CLASS)) { return target; } target = target.parentNode; } return null; }, _startDrag: function(e) { var _this = this; this._isDragging = false; // Check if this is a reorder drag if(ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_DRAG_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) { var item = this._getItem(e.target); if(item) { this._dragOp = new ReorderDrag({ el: item, scrollEl: this.scrollEl, scrollView: this.scrollView, onReorder: function(el, start, end) { _this.onReorder && _this.onReorder(el, start, end); } }); this._dragOp.start(e); e.preventDefault(); return; } } // Or check if this is a swipe to the side drag else if((e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) { this._dragOp = new SlideDrag({ el: this.el }); this._dragOp.start(e); e.preventDefault(); return; } // We aren't handling it, so pass it up the chain //ionic.views.ListView.__super__._startDrag.call(this, e); }, _handleEndDrag: function(e) { var _this = this; if(!this._dragOp) { //ionic.views.ListView.__super__._handleEndDrag.call(this, e); return; } // Cancel touch timeout clearTimeout(this._touchTimeout); var items = _this.el.querySelectorAll('.item'); for(var i = 0, l = items.length; i < l; i++) { items[i].classList.remove('active'); } this._dragOp.end(e, function() { _this._initDrag(); }); }, /** * Process the drag event to move the item to the left or right. */ _handleDrag: function(e) { var _this = this, content, buttons; // If the user has a touch timeout to highlight an element, clear it if we // get sufficient draggage if(Math.abs(e.gesture.deltaX) > 10 || Math.abs(e.gesture.deltaY) > 10) { clearTimeout(this._touchTimeout); } clearTimeout(this._touchTimeout); // If we get a drag event, make sure we aren't in another drag, then check if we should // start one if(!this.isDragging && !this._dragOp) { this._startDrag(e); } // No drag still, pass it up if(!this._dragOp) { //ionic.views.ListView.__super__._handleDrag.call(this, e); return; } e.gesture.srcEvent.preventDefault(); this._dragOp.drag(e); }, /** * Handle the touch event to show the active state on an item if necessary. */ _handleTouch: function(e) { var _this = this; var item = ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_CLASS); if(!item) { return; } this._touchTimeout = setTimeout(function() { var items = _this.el.querySelectorAll('.item'); for(var i = 0, l = items.length; i < l; i++) { items[i].classList.remove('active'); } item.classList.add('active'); }, 250); }, }); })(ionic); ; (function(ionic) { 'use strict'; /** * Loading * * The Loading is an overlay that can be used to indicate * activity while blocking user interaction. */ ionic.views.Loading = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; this.el = opts.el; this.maxWidth = opts.maxWidth || 200; this.showDelay = opts.showDelay || 0; this._loadingBox = this.el.querySelector('.loading'); }, show: function() { var _this = this; if(this._loadingBox) { var lb = _this._loadingBox; var width = Math.min(_this.maxWidth, Math.max(window.outerWidth - 40, lb.offsetWidth)); lb.style.width = width + 'px'; lb.style.marginLeft = (-lb.offsetWidth) / 2 + 'px'; lb.style.marginTop = (-lb.offsetHeight) / 2 + 'px'; // Wait 'showDelay' ms before showing the loading screen this._showDelayTimeout = window.setTimeout(function() { _this.el.classList.add('active'); }, _this.showDelay); } }, hide: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; // Prevent unnecessary 'show' after 'hide' has already been called window.clearTimeout(this._showDelayTimeout); this.el.classList.remove('active'); } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.Modal = ionic.views.View.inherit({ initialize: function(opts) { opts = ionic.extend({ focusFirstInput: false, unfocusOnHide: true, focusFirstDelay: 600 }, opts); ionic.extend(this, opts); this.el = opts.el; }, show: function() { var self = this; this.el.classList.add('active'); if(this.focusFirstInput) { // Let any animations run first window.setTimeout(function() { var input = self.el.querySelector('input, textarea'); input && input.focus && input.focus(); }, this.focusFirstDelay); } }, hide: function() { this.el.classList.remove('active'); // Unfocus all elements if(this.unfocusOnHide) { var inputs = this.el.querySelectorAll('input, textarea'); // Let any animations run first window.setTimeout(function() { for(var i = 0; i < inputs.length; i++) { inputs[i].blur && inputs[i].blur(); } }); } } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.NavBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this._titleEl = this.el.querySelector('.title'); if(opts.hidden) { this.hide(); } }, hide: function() { this.el.classList.add('hidden'); }, show: function() { this.el.classList.remove('hidden'); }, shouldGoBack: function() {}, setTitle: function(title) { if(!this._titleEl) { return; } this._titleEl.innerHTML = title; }, showBackButton: function(shouldShow) { var _this = this; if(!this._currentBackButton) { var back = document.createElement('a'); back.className = 'button back'; back.innerHTML = 'Back'; this._currentBackButton = back; this._currentBackButton.onclick = function(event) { _this.shouldGoBack && _this.shouldGoBack(); }; } if(shouldShow && !this._currentBackButton.parentNode) { // Prepend the back button this.el.insertBefore(this._currentBackButton, this.el.firstChild); } else if(!shouldShow && this._currentBackButton.parentNode) { // Remove the back button if it's there this._currentBackButton.parentNode.removeChild(this._currentBackButton); } } }); })(ionic); ; (function(ionic) { 'use strict'; /** * An ActionSheet is the slide up menu popularized on iOS. * * You see it all over iOS apps, where it offers a set of options * triggered after an action. */ ionic.views.Popup = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; this.el = opts.el; }, setTitle: function(title) { var titleEl = el.querySelector('.popup-title'); if(titleEl) { titleEl.innerHTML = title; } }, alert: function(message) { var _this = this; ionic.requestAnimationFrame(function() { _this.setTitle(message); _this.el.classList.add('active'); }); }, hide: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.remove('active'); } }); })(ionic); ; (function(ionic) { 'use strict'; /** * The side menu view handles one of the side menu's in a Side Menu Controller * configuration. * It takes a DOM reference to that side menu element. */ ionic.views.SideMenu = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.isEnabled = opts.isEnabled || true; this.setWidth(opts.width); }, getFullWidth: function() { return this.width; }, setWidth: function(width) { this.width = width; this.el.style.width = width + 'px'; }, setIsEnabled: function(isEnabled) { this.isEnabled = isEnabled; }, bringUp: function() { if(this.el.style.zIndex !== '0') { this.el.style.zIndex = '0'; } }, pushDown: function() { if(this.el.style.zIndex !== '-1') { this.el.style.zIndex = '-1'; } } }); ionic.views.SideMenuContent = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; ionic.extend(this, { animationClass: 'menu-animated', onDrag: function(e) {}, onEndDrag: function(e) {}, }, opts); ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el); ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el); }, _onDrag: function(e) { this.onDrag && this.onDrag(e); }, _onEndDrag: function(e) { this.onEndDrag && this.onEndDrag(e); }, disableAnimation: function() { this.el.classList.remove(this.animationClass); }, enableAnimation: function() { this.el.classList.add(this.animationClass); }, getTranslateX: function() { return parseFloat(this.el.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]); }, setTranslateX: ionic.animationFrameThrottle(function(x) { this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(' + x + 'px, 0, 0)'; }) }); })(ionic); ; /* * Adapted from Swipe.js 2.0 * * Brad Birdsall * Copyright 2013, MIT License * */ (function(ionic) { 'use strict'; ionic.views.Slider = ionic.views.View.inherit({ initialize: function (options) { // utilities var noop = function() {}; // simple no operation function var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution // check browser capabilities var browser = { addEventListener: !!window.addEventListener, touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch, transitions: (function(temp) { var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition']; for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true; return false; })(document.createElement('swipe')) }; var container = options.el; // quit if no root element if (!container) return; var element = container.children[0]; var slides, slidePos, width, length; options = options || {}; var index = parseInt(options.startSlide, 10) || 0; var speed = options.speed || 300; options.continuous = options.continuous !== undefined ? options.continuous : true; function setup() { // cache slides slides = element.children; length = slides.length; // set continuous to false if only one slide if (slides.length < 2) options.continuous = false; //special case if two slides if (browser.transitions && options.continuous && slides.length < 3) { element.appendChild(slides[0].cloneNode(true)); element.appendChild(element.children[1].cloneNode(true)); slides = element.children; } // create an array to store current positions of each slide slidePos = new Array(slides.length); // determine width of each slide width = container.getBoundingClientRect().width || container.offsetWidth; element.style.width = (slides.length * width) + 'px'; // stack elements var pos = slides.length; while(pos--) { var slide = slides[pos]; slide.style.width = width + 'px'; slide.setAttribute('data-index', pos); if (browser.transitions) { slide.style.left = (pos * -width) + 'px'; move(pos, index > pos ? -width : (index < pos ? width : 0), 0); } } // reposition elements before and after index if (options.continuous && browser.transitions) { move(circle(index-1), -width, 0); move(circle(index+1), width, 0); } if (!browser.transitions) element.style.left = (index * -width) + 'px'; container.style.visibility = 'visible'; options.slidesChanged && options.slidesChanged(); } function prev() { if (options.continuous) slide(index-1); else if (index) slide(index-1); } function next() { if (options.continuous) slide(index+1); else if (index < slides.length - 1) slide(index+1); } function circle(index) { // a simple positive modulo using slides.length return (slides.length + (index % slides.length)) % slides.length; } function slide(to, slideSpeed) { // do nothing if already on requested slide if (index == to) return; if (browser.transitions) { var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward // get the actual position of the slide if (options.continuous) { var natural_direction = direction; direction = -slidePos[circle(to)] / width; // if going forward but to < index, use to = slides.length + to // if going backward but to > index, use to = -slides.length + to if (direction !== natural_direction) to = -direction * slides.length + to; } var diff = Math.abs(index-to) - 1; // move all the slides between index and to in the right direction while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0); to = circle(to); move(index, width * direction, slideSpeed || speed); move(to, 0, slideSpeed || speed); if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place } else { to = circle(to); animate(index * -width, to * -width, slideSpeed || speed); //no fallback for a circular continuous if the browser does not accept transitions } index = to; offloadFn(options.callback && options.callback(index, slides[index])); } function move(index, dist, speed) { translate(index, dist, speed); slidePos[index] = dist; } function translate(index, dist, speed) { var slide = slides[index]; var style = slide && slide.style; if (!style) return; style.webkitTransitionDuration = style.MozTransitionDuration = style.msTransitionDuration = style.OTransitionDuration = style.transitionDuration = speed + 'ms'; style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)'; style.msTransform = style.MozTransform = style.OTransform = 'translateX(' + dist + 'px)'; } function animate(from, to, speed) { // if not an animation, just reposition if (!speed) { element.style.left = to + 'px'; return; } var start = +new Date; var timer = setInterval(function() { var timeElap = +new Date - start; if (timeElap > speed) { element.style.left = to + 'px'; if (delay) begin(); options.transitionEnd && options.transitionEnd.call(event, index, slides[index]); clearInterval(timer); return; } element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px'; }, 4); } // setup auto slideshow var delay = options.auto || 0; var interval; function begin() { interval = setTimeout(next, delay); } function stop() { delay = options.auto || 0; clearTimeout(interval); } // setup initial vars var start = {}; var delta = {}; var isScrolling; // setup event capturing var events = { handleEvent: function(event) { if(event.type == 'mousedown' || event.type == 'mouseup' || event.type == 'mousemove') { event.touches = [{ pageX: event.pageX, pageY: event.pageY }]; } switch (event.type) { case 'mousedown': this.start(event); break; case 'touchstart': this.start(event); break; case 'touchmove': this.move(event); break; case 'mousemove': this.move(event); break; case 'touchend': offloadFn(this.end(event)); break; case 'mouseup': offloadFn(this.end(event)); break; case 'webkitTransitionEnd': case 'msTransitionEnd': case 'oTransitionEnd': case 'otransitionend': case 'transitionend': offloadFn(this.transitionEnd(event)); break; case 'resize': offloadFn(setup); break; } if (options.stopPropagation) event.stopPropagation(); }, start: function(event) { var touches = event.touches[0]; // measure start values start = { // get initial touch coords x: touches.pageX, y: touches.pageY, // store time to determine touch duration time: +new Date }; // used for testing first move event isScrolling = undefined; // reset delta and end measurements delta = {}; // attach touchmove and touchend listeners if(browser.touch) { element.addEventListener('touchmove', this, false); element.addEventListener('touchend', this, false); } else { element.addEventListener('mousemove', this, false); element.addEventListener('mouseup', this, false); document.addEventListener('mouseup', this, false); } }, move: function(event) { // ensure swiping with one touch and not pinching if ( event.touches.length > 1 || event.scale && event.scale !== 1) return if (options.disableScroll) event.preventDefault(); var touches = event.touches[0]; // measure change in x and y delta = { x: touches.pageX - start.x, y: touches.pageY - start.y } // determine if scrolling test has run - one time test if ( typeof isScrolling == 'undefined') { isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) ); } // if user is not trying to scroll vertically if (!isScrolling) { // prevent native scrolling event.preventDefault(); // stop slideshow stop(); // increase resistance if first or last slide if (options.continuous) { // we don't add resistance at the end translate(circle(index-1), delta.x + slidePos[circle(index-1)], 0); translate(index, delta.x + slidePos[index], 0); translate(circle(index+1), delta.x + slidePos[circle(index+1)], 0); } else { delta.x = delta.x / ( (!index && delta.x > 0 // if first slide and sliding left || index == slides.length - 1 // or if last slide and sliding right && delta.x < 0 // and if sliding at all ) ? ( Math.abs(delta.x) / width + 1 ) // determine resistance level : 1 ); // no resistance if false // translate 1:1 translate(index-1, delta.x + slidePos[index-1], 0); translate(index, delta.x + slidePos[index], 0); translate(index+1, delta.x + slidePos[index+1], 0); } } }, end: function(event) { // measure duration var duration = +new Date - start.time; // determine if slide attempt triggers next/prev slide var isValidSlide = Number(duration) < 250 // if slide duration is less than 250ms && Math.abs(delta.x) > 20 // and if slide amt is greater than 20px || Math.abs(delta.x) > width/2; // or if slide amt is greater than half the width // determine if slide attempt is past start and end var isPastBounds = !index && delta.x > 0 // if first slide and slide amt is greater than 0 || index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0 if (options.continuous) isPastBounds = false; // determine direction of swipe (true:right, false:left) var direction = delta.x < 0; // if not scrolling vertically if (!isScrolling) { if (isValidSlide && !isPastBounds) { if (direction) { if (options.continuous) { // we need to get the next in this direction in place move(circle(index-1), -width, 0); move(circle(index+2), width, 0); } else { move(index-1, -width, 0); } move(index, slidePos[index]-width, speed); move(circle(index+1), slidePos[circle(index+1)]-width, speed); index = circle(index+1); } else { if (options.continuous) { // we need to get the next in this direction in place move(circle(index+1), width, 0); move(circle(index-2), -width, 0); } else { move(index+1, width, 0); } move(index, slidePos[index]+width, speed); move(circle(index-1), slidePos[circle(index-1)]+width, speed); index = circle(index-1); } options.callback && options.callback(index, slides[index]); } else { if (options.continuous) { move(circle(index-1), -width, speed); move(index, 0, speed); move(circle(index+1), width, speed); } else { move(index-1, -width, speed); move(index, 0, speed); move(index+1, width, speed); } } } // kill touchmove and touchend event listeners until touchstart called again if(browser.touch) { element.removeEventListener('touchmove', events, false) element.removeEventListener('touchend', events, false) } else { element.removeEventListener('mousemove', events, false) element.removeEventListener('mouseup', events, false) document.removeEventListener('mouseup', events, false); } }, transitionEnd: function(event) { if (parseInt(event.target.getAttribute('data-index'), 10) == index) { if (delay) begin(); options.transitionEnd && options.transitionEnd.call(event, index, slides[index]); } } } // Public API this.setup = function() { setup(); }; this.slide = function(to, speed) { // cancel slideshow stop(); slide(to, speed); }; this.prev = function() { // cancel slideshow stop(); prev(); }; this.next = function() { // cancel slideshow stop(); next(); }; this.stop = function() { // cancel slideshow stop(); }; this.getPos = function() { // return current index position return index; }; this.getNumSlides = function() { // return total number of slides return length; }; this.kill = function() { // cancel slideshow stop(); // reset element element.style.width = ''; element.style.left = ''; // reset slides var pos = slides.length; while(pos--) { var slide = slides[pos]; slide.style.width = ''; slide.style.left = ''; if (browser.transitions) translate(pos, 0, 0); } // removed event listeners if (browser.addEventListener) { // remove current event listeners element.removeEventListener('touchstart', events, false); element.removeEventListener('webkitTransitionEnd', events, false); element.removeEventListener('msTransitionEnd', events, false); element.removeEventListener('oTransitionEnd', events, false); element.removeEventListener('otransitionend', events, false); element.removeEventListener('transitionend', events, false); window.removeEventListener('resize', events, false); } else { window.onresize = null; } }; this.load = function() { // trigger setup setup(); // start auto slideshow if applicable if (delay) begin(); // add event listeners if (browser.addEventListener) { // set touchstart event on element if (browser.touch) { element.addEventListener('touchstart', events, false); } else { element.addEventListener('mousedown', events, false); } if (browser.transitions) { element.addEventListener('webkitTransitionEnd', events, false); element.addEventListener('msTransitionEnd', events, false); element.addEventListener('oTransitionEnd', events, false); element.addEventListener('otransitionend', events, false); element.addEventListener('transitionend', events, false); } // set resize event on window window.addEventListener('resize', events, false); } else { window.onresize = function () { setup() }; // to play nice with old IE } } } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.TabBarItem = ionic.views.View.inherit({ initialize: function(el) { this.el = el; this._buildItem(); }, // Factory for creating an item from a given javascript object create: function(itemData) { var item = document.createElement('a'); item.className = 'tab-item'; // If there is an icon, add the icon element if(itemData.icon) { var icon = document.createElement('i'); icon.className = itemData.icon; item.appendChild(icon); } // If there is a badge, add the badge element if(itemData.badge) { var badge = document.createElement('i'); badge.className = 'badge'; badge.innerHTML = itemData.badge; item.appendChild(badge); item.className = 'tab-item has-badge'; } item.appendChild(document.createTextNode(itemData.title)); return new ionic.views.TabBarItem(item); }, _buildItem: function() { var _this = this, child, children = Array.prototype.slice.call(this.el.children); for(var i = 0, j = children.length; i < j; i++) { child = children[i]; // Test if this is a "i" tag with icon in the class name // TODO: This heuristic might not be sufficient if(child.tagName.toLowerCase() == 'i' && /icon/.test(child.className)) { this.icon = child.className; } // Test if this is a "i" tag with badge in the class name // TODO: This heuristic might not be sufficient if(child.tagName.toLowerCase() == 'i' && /badge/.test(child.className)) { this.badge = child.textContent.trim(); } } this.title = ''; for(i = 0, j = this.el.childNodes.length; i < j; i++) { child = this.el.childNodes[i]; if (child.nodeName === "#text") { this.title += child.nodeValue.trim(); } } this._tapHandler = function(e) { _this.onTap && _this.onTap(e); }; ionic.on('tap', this._tapHandler, this.el); }, onTap: function(e) { }, // Remove the event listeners from this object destroy: function() { ionic.off('tap', this._tapHandler, this.el); }, getIcon: function() { return this.icon; }, getTitle: function() { return this.title; }, getBadge: function() { return this.badge; }, setSelected: function(isSelected) { this.isSelected = isSelected; if(isSelected) { this.el.classList.add('active'); } else { this.el.classList.remove('active'); } } }); ionic.views.TabBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.items = []; this._buildItems(); }, // get all the items for the TabBar getItems: function() { return this.items; }, // Add an item to the tab bar addItem: function(item) { // Create a new TabItem var tabItem = ionic.views.TabBarItem.prototype.create(item); this.appendItemElement(tabItem); this.items.push(tabItem); this._bindEventsOnItem(tabItem); }, appendItemElement: function(item) { if(!this.el) { return; } this.el.appendChild(item.el); }, // Remove an item from the tab bar removeItem: function(index) { var item = this.items[index]; if(!item) { return; } item.onTap = undefined; item.destroy(); }, _bindEventsOnItem: function(item) { var _this = this; if(!this._itemTapHandler) { this._itemTapHandler = function(e) { //_this.selectItem(this); _this.trySelectItem(this); }; } item.onTap = this._itemTapHandler; }, // Get the currently selected item getSelectedItem: function() { return this.selectedItem; }, // Set the currently selected item by index setSelectedItem: function(index) { this.selectedItem = this.items[index]; // Deselect all for(var i = 0, j = this.items.length; i < j; i += 1) { this.items[i].setSelected(false); } // Select the new item if(this.selectedItem) { this.selectedItem.setSelected(true); //this.onTabSelected && this.onTabSelected(this.selectedItem, index); } }, // Select the given item assuming we can find it in our // item list. selectItem: function(item) { for(var i = 0, j = this.items.length; i < j; i += 1) { if(this.items[i] == item) { this.setSelectedItem(i); return; } } }, // Try to select a given item. This triggers an event such // that the view controller managing this tab bar can decide // whether to select the item or cancel it. trySelectItem: function(item) { for(var i = 0, j = this.items.length; i < j; i += 1) { if(this.items[i] == item) { this.tryTabSelect && this.tryTabSelect(i); return; } } }, // Build the initial items list from the given DOM node. _buildItems: function() { var item, items = Array.prototype.slice.call(this.el.children); for(var i = 0, j = items.length; i < j; i += 1) { item = new ionic.views.TabBarItem(items[i]); this.items[i] = item; this._bindEventsOnItem(item); } if(this.items.length > 0) { this.selectedItem = this.items[0]; } }, // Destroy this tab bar destroy: function() { for(var i = 0, j = this.items.length; i < j; i += 1) { this.items[i].destroy(); } this.items.length = 0; } }); })(window.ionic); ; (function(ionic) { 'use strict'; ionic.views.Toggle = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.checkbox = opts.checkbox; this.track = opts.track; this.handle = opts.handle; this.openPercent = -1; }, tap: function(e) { if(this.el.getAttribute('disabled') !== 'disabled') { this.val( !this.checkbox.checked ); } }, drag: function(e) { var slidePageLeft = this.track.offsetLeft + (this.handle.offsetWidth / 2); var slidePageRight = this.track.offsetLeft + this.track.offsetWidth - (this.handle.offsetWidth / 2); if(e.pageX >= slidePageRight - 4) { this.val(true); } else if(e.pageX <= slidePageLeft) { this.val(false); } else { this.setOpenPercent( Math.round( (1 - ((slidePageRight - e.pageX) / (slidePageRight - slidePageLeft) )) * 100) ); } }, setOpenPercent: function(openPercent) { // only make a change if the new open percent has changed if(this.openPercent < 0 || (openPercent < (this.openPercent - 3) || openPercent > (this.openPercent + 3) ) ) { this.openPercent = openPercent; if(openPercent === 0) { this.val(false); } else if(openPercent === 100) { this.val(true); } else { var openPixel = Math.round( (openPercent / 100) * this.track.offsetWidth - (this.handle.offsetWidth) ); openPixel = (openPixel < 1 ? 0 : openPixel); this.handle.style[ionic.CSS.TRANSFORM] = 'translate3d(' + openPixel + 'px,0,0)'; } } }, release: function(e) { this.val( this.openPercent >= 50 ); }, val: function(value) { if(value === true || value === false) { if(this.handle.style[ionic.CSS.TRANSFORM] !== "") { this.handle.style[ionic.CSS.TRANSFORM] = ""; } this.checkbox.checked = value; this.openPercent = (value ? 100 : 0); } return this.checkbox.checked; } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.controllers.ViewController = function(options) { this.initialize.apply(this, arguments); }; ionic.controllers.ViewController.inherit = ionic.inherit; ionic.extend(ionic.controllers.ViewController.prototype, { initialize: function() {}, // Destroy this view controller, including all child views destroy: function() { } }); })(window.ionic); ; (function(ionic) { 'use strict'; /** * The NavController makes it easy to have a stack * of views or screens that can be pushed and popped * for a dynamic navigation flow. This API is modelled * off of the UINavigationController in iOS. * * The NavController can drive a nav bar to show a back button * if the stack can be poppped to go back to the last view, and * it will handle updating the title of the nav bar and processing animations. */ ionic.controllers.NavController = ionic.controllers.ViewController.inherit({ initialize: function(opts) { var _this = this; this.navBar = opts.navBar; this.content = opts.content; this.controllers = opts.controllers || []; this._updateNavBar(); // TODO: Is this the best way? this.navBar.shouldGoBack = function() { _this.pop(); }; }, /** * @return {array} the array of controllers on the stack. */ getControllers: function() { return this.controllers; }, /** * @return {object} the controller at the top of the stack. */ getTopController: function() { return this.controllers[this.controllers.length-1]; }, /** * Push a new controller onto the navigation stack. The new controller * will automatically become the new visible view. * * @param {object} controller the controller to push on the stack. */ push: function(controller) { var last = this.controllers[this.controllers.length - 1]; this.controllers.push(controller); // Indicate we are switching controllers var shouldSwitch = this.switchingController && this.switchingController(controller) || true; // Return if navigation cancelled if(shouldSwitch === false) return; // Actually switch the active controllers if(last) { last.isVisible = false; last.visibilityChanged && last.visibilityChanged('push'); } // Grab the top controller on the stack var next = this.controllers[this.controllers.length - 1]; next.isVisible = true; // Trigger visibility change, but send 'first' if this is the first page next.visibilityChanged && next.visibilityChanged(last ? 'push' : 'first'); this._updateNavBar(); return controller; }, /** * Pop the top controller off the stack, and show the last one. This is the * "back" operation. * * @return {object} the last popped controller */ pop: function() { var next, last; // Make sure we keep one on the stack at all times if(this.controllers.length < 2) { return; } // Grab the controller behind the top one on the stack last = this.controllers.pop(); if(last) { last.isVisible = false; last.visibilityChanged && last.visibilityChanged('pop'); } // Remove the old one //last && last.detach(); next = this.controllers[this.controllers.length - 1]; // TODO: No DOM stuff here //this.content.el.appendChild(next.el); next.isVisible = true; next.visibilityChanged && next.visibilityChanged('pop'); // Switch to it (TODO: Animate or such things here) this._updateNavBar(); return last; }, /** * Show the NavBar (if any) */ showNavBar: function() { if(this.navBar) { this.navBar.show(); } }, /** * Hide the NavBar (if any) */ hideNavBar: function() { if(this.navBar) { this.navBar.hide(); } }, // Update the nav bar after a push or pop _updateNavBar: function() { if(!this.getTopController() || !this.navBar) { return; } this.navBar.setTitle(this.getTopController().title); if(this.controllers.length > 1) { this.navBar.showBackButton(true); } else { this.navBar.showBackButton(false); } } }); })(window.ionic); ; (function(ionic) { 'use strict'; /** * The SideMenuController is a controller with a left and/or right menu that * can be slid out and toggled. Seen on many an app. * * The right or left menu can be disabled or not used at all, if desired. */ ionic.controllers.SideMenuController = ionic.controllers.ViewController.inherit({ initialize: function(options) { var self = this; this.left = options.left; this.right = options.right; this.content = options.content; this.dragThresholdX = options.dragThresholdX || 10; this._rightShowing = false; this._leftShowing = false; this._isDragging = false; if(this.content) { this.content.onDrag = function(e) { self._handleDrag(e); }; this.content.onEndDrag =function(e) { self._endDrag(e); }; } }, /** * Set the content view controller if not passed in the constructor options. * * @param {object} content */ setContent: function(content) { var self = this; this.content = content; this.content.onDrag = function(e) { self._handleDrag(e); }; this.content.endDrag = function(e) { self._endDrag(e); }; }, /** * Toggle the left menu to open 100% */ toggleLeft: function() { this.content.enableAnimation(); var openAmount = this.getOpenAmount(); if(openAmount > 0) { this.openPercentage(0); } else { this.openPercentage(100); } }, /** * Toggle the right menu to open 100% */ toggleRight: function() { this.content.enableAnimation(); var openAmount = this.getOpenAmount(); if(openAmount < 0) { this.openPercentage(0); } else { this.openPercentage(-100); } }, /** * Close all menus. */ close: function() { this.openPercentage(0); }, /** * @return {float} The amount the side menu is open, either positive or negative for left (positive), or right (negative) */ getOpenAmount: function() { return this.content && this.content.getTranslateX() || 0; }, /** * @return {float} The ratio of open amount over menu width. For example, a * menu of width 100 open 50 pixels would be open 50% or a ratio of 0.5. Value is negative * for right menu. */ getOpenRatio: function() { var amount = this.getOpenAmount(); if(amount >= 0) { return amount / this.left.width; } return amount / this.right.width; }, isOpen: function() { return this.getOpenRatio() == 1; }, /** * @return {float} The percentage of open amount over menu width. For example, a * menu of width 100 open 50 pixels would be open 50%. Value is negative * for right menu. */ getOpenPercentage: function() { return this.getOpenRatio() * 100; }, /** * Open the menu with a given percentage amount. * @param {float} percentage The percentage (positive or negative for left/right) to open the menu. */ openPercentage: function(percentage) { var p = percentage / 100; if(this.left && percentage >= 0) { this.openAmount(this.left.width * p); } else if(this.right && percentage < 0) { var maxRight = this.right.width; this.openAmount(this.right.width * p); } }, /** * Open the menu the given pixel amount. * @param {float} amount the pixel amount to open the menu. Positive value for left menu, * negative value for right menu (only one menu will be visible at a time). */ openAmount: function(amount) { var maxLeft = this.left && this.left.width || 0; var maxRight = this.right && this.right.width || 0; // Check if we can move to that side, depending if the left/right panel is enabled if((!(this.left && this.left.isEnabled) && amount > 0) || (!(this.right && this.right.isEnabled) && amount < 0)) { return; } if((this._leftShowing && amount > maxLeft) || (this._rightShowing && amount < -maxRight)) { return; } this.content.setTranslateX(amount); if(amount >= 0) { this._leftShowing = true; this._rightShowing = false; // Push the z-index of the right menu down this.right && this.right.pushDown && this.right.pushDown(); // Bring the z-index of the left menu up this.left && this.left.bringUp && this.left.bringUp(); } else { this._rightShowing = true; this._leftShowing = false; // Bring the z-index of the right menu up this.right && this.right.bringUp && this.right.bringUp(); // Push the z-index of the left menu down this.left && this.left.pushDown && this.left.pushDown(); } }, /** * Given an event object, find the final resting position of this side * menu. For example, if the user "throws" the content to the right and * releases the touch, the left menu should snap open (animated, of course). * * @param {Event} e the gesture event to use for snapping */ snapToRest: function(e) { // We want to animate at the end of this this.content.enableAnimation(); this._isDragging = false; // Check how much the panel is open after the drag, and // what the drag velocity is var ratio = this.getOpenRatio(); if(ratio === 0) return; var velocityThreshold = 0.3; var velocityX = e.gesture.velocityX; var direction = e.gesture.direction; // Less than half, going left //if(ratio > 0 && ratio < 0.5 && direction == 'left' && velocityX < velocityThreshold) { //this.openPercentage(0); //} // Going right, less than half, too slow (snap back) if(ratio > 0 && ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) { this.openPercentage(0); } // Going left, more than half, too slow (snap back) else if(ratio > 0.5 && direction == 'left' && velocityX < velocityThreshold) { this.openPercentage(100); } // Going left, less than half, too slow (snap back) else if(ratio < 0 && ratio > -0.5 && direction == 'left' && velocityX < velocityThreshold) { this.openPercentage(0); } // Going right, more than half, too slow (snap back) else if(ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) { this.openPercentage(-100); } // Going right, more than half, or quickly (snap open) else if(direction == 'right' && ratio >= 0 && (ratio >= 0.5 || velocityX > velocityThreshold)) { this.openPercentage(100); } // Going left, more than half, or quickly (span open) else if(direction == 'left' && ratio <= 0 && (ratio <= -0.5 || velocityX > velocityThreshold)) { this.openPercentage(-100); } // Snap back for safety else { this.openPercentage(0); } }, // End a drag with the given event _endDrag: function(e) { if(this._isDragging) { this.snapToRest(e); } this._startX = null; this._lastX = null; this._offsetX = null; }, // Handle a drag event _handleDrag: function(e) { // If we don't have start coords, grab and store them if(!this._startX) { this._startX = e.gesture.touches[0].pageX; this._lastX = this._startX; } else { // Grab the current tap coords this._lastX = e.gesture.touches[0].pageX; } // Calculate difference from the tap points if(!this._isDragging && Math.abs(this._lastX - this._startX) > this.dragThresholdX) { // if the difference is greater than threshold, start dragging using the current // point as the starting point this._startX = this._lastX; this._isDragging = true; // Initialize dragging this.content.disableAnimation(); this._offsetX = this.getOpenAmount(); } if(this._isDragging) { this.openAmount(this._offsetX + (this._lastX - this._startX)); } } }); })(ionic); ; (function(ionic) { 'use strict'; /** * The TabBarController handles a set of view controllers powered by a tab strip * at the bottom (or possibly top) of a screen. * * The API here is somewhat modelled off of UITabController in the sense that the * controllers actually define what the tab will look like (title, icon, etc.). * * Tabs shouldn't be interacted with through your own code. Instead, use the controller * methods which will power the tab bar. */ ionic.controllers.TabBarController = ionic.controllers.ViewController.inherit({ initialize: function(options) { this.tabBar = options.tabBar; this._bindEvents(); this.controllers = []; var controllers = options.controllers || []; for(var i = 0; i < controllers.length; i++) { this.addController(controllers[i]); } // Bind or set our tabWillChange callback this.controllerWillChange = options.controllerWillChange || function(controller) {}; this.controllerChanged = options.controllerChanged || function(controller) {}; // Try to select the first controller if we have one this.setSelectedController(0); }, // Start listening for events on our tab bar _bindEvents: function() { var _this = this; this.tabBar.tryTabSelect = function(index) { _this.setSelectedController(index); }; }, selectController: function(index) { var shouldChange = true; // Check if we should switch to this tab. This lets the app // cancel tab switches if the context isn't right, for example. if(this.controllerWillChange) { if(this.controllerWillChange(this.controllers[index], index) === false) { shouldChange = false; } } if(shouldChange) { this.setSelectedController(index); } }, // Force the selection of a controller at the given index setSelectedController: function(index) { if(index >= this.controllers.length) { return; } var lastController = this.selectedController; var lastIndex = this.selectedIndex; this.selectedController = this.controllers[index]; this.selectedIndex = index; this._showController(index); this.tabBar.setSelectedItem(index); this.controllerChanged && this.controllerChanged(lastController, lastIndex, this.selectedController, this.selectedIndex); }, _showController: function(index) { var c; for(var i = 0, j = this.controllers.length; i < j; i ++) { c = this.controllers[i]; //c.detach && c.detach(); c.isVisible = false; c.visibilityChanged && c.visibilityChanged(); } c = this.controllers[index]; //c.attach && c.attach(); c.isVisible = true; c.visibilityChanged && c.visibilityChanged(); }, _clearSelected: function() { this.selectedController = null; this.selectedIndex = -1; }, // Return the tab at the given index getController: function(index) { return this.controllers[index]; }, // Return the current tab list getControllers: function() { return this.controllers; }, // Get the currently selected controller getSelectedController: function() { return this.selectedController; }, // Get the index of the currently selected controller getSelectedControllerIndex: function() { return this.selectedIndex; }, // Add a tab addController: function(controller) { this.controllers.push(controller); this.tabBar.addItem({ title: controller.title, icon: controller.icon, badge: controller.badge }); // If we don't have a selected controller yet, select the first one. if(!this.selectedController) { this.setSelectedController(0); } }, // Set the tabs and select the first setControllers: function(controllers) { this.controllers = controllers; this._clearSelected(); this.selectController(0); }, }); })(window.ionic);
contribs/docbook-xsl-1.78.1/webhelp/template/search/nwSearchFnt.js
alastrina123/debrief
/*---------------------------------------------------------------------------- * JavaScript for webhelp search *---------------------------------------------------------------------------- This file is part of the webhelpsearch plugin for DocBook WebHelp Copyright (c) 2007-2008 NexWave Solutions All Rights Reserved. www.nexwave.biz Nadege Quaine http://kasunbg.blogspot.com/ Kasun Gajasinghe */ //string initialization var htmlfileList = "htmlFileInfoList.js"; var htmlfileinfoList = "htmlFileInfoList.js"; var useCJKTokenizing = false; var w = new Object(); var scoring = new Object(); var searchTextField = ''; var no = 0; var noWords = 0; var partialSearch = "<font class=\"highlightText\">There is no page containing all the search terms.<br>Partial results:</font>"; var warningMsg = '<div style="padding: 5px;margin-right:5px;;background-color:#FFFF00;">'; warningMsg+='<b>Please note that due to security settings, Google Chrome does not highlight'; warningMsg+=' the search results in the right frame.</b><br>'; warningMsg+='This happens only when the WebHelp files are loaded from the local file system.<br>'; warningMsg+='Workarounds:'; warningMsg+='<ul>'; warningMsg+='<li>Try using another web browser.</li>'; warningMsg+='<li>Deploy the WebHelp files on a web server.</li>'; warningMsg+='</div>'; txt_filesfound = 'Results'; txt_enter_at_least_1_char = "You must enter at least one character."; txt_enter_more_than_10_words = "Only first 10 words will be processed."; txt_browser_not_supported = "Your browser is not supported. Use of Mozilla Firefox is recommended."; txt_please_wait = "Please wait. Search in progress..."; txt_results_for = "Results for: "; /* This function verify the validity of search input by the user Cette fonction verifie la validite de la recherche entrre par l utilisateur */ function Verifie(searchForm) { // Check browser compatibility if (navigator.userAgent.indexOf("Konquerer") > -1) { alert(txt_browser_not_supported); return; } searchTextField = trim(document.searchForm.textToSearch.value); searchTextField = searchTextField.replace(/['"]/g,''); var expressionInput = searchTextField; $.cookie('textToSearch', expressionInput); if (expressionInput.length < 1) { // expression is invalid alert(txt_enter_at_least_1_char); // reactive la fenetre de search (utile car cadres) document.searchForm.textToSearch.focus(); } else { var splitSpace = searchTextField.split(" "); var splitWords = []; for (var i = 0 ; i < splitSpace.length ; i++) { var splitDot = splitSpace[i].split("."); if(!(splitDot.length == 1)){ splitWords.push(splitSpace[i]); } for (var i1 = 0; i1 < splitDot.length; i1++) { var splitColon = splitDot[i1].split(":"); for (var i2 = 0; i2 < splitColon.length; i2++) { var splitDash = splitColon[i2].split("-"); for (var i3 = 0; i3 < splitDash.length; i3++) { if (splitDash[i3].split("").length > 0) { splitWords.push(splitDash[i3]); } } } } } noWords = splitWords; if (noWords.length > 9){ // Allow to search maximum 10 words alert(txt_enter_more_than_10_words); expressionInput = ''; for (var x = 0 ; x < 10 ; x++){ expressionInput = expressionInput + " " + noWords[x]; } Effectuer_recherche(expressionInput); document.searchForm.textToSearch.focus(); } else { // Effectuer la recherche expressionInput = ''; for (var x = 0 ; x < noWords.length ; x++) { expressionInput = expressionInput + " " + noWords[x]; } Effectuer_recherche(expressionInput); // reactive la fenetre de search (utile car cadres) document.searchForm.textToSearch.focus(); } } } var stemQueryMap = new Array(); // A hashtable which maps stems to query words /* This function parses the search expression, loads the indices and displays the results*/ function Effectuer_recherche(expressionInput) { /* Display a waiting message */ //DisplayWaitingMessage(); /*data initialisation*/ var searchFor = ""; // expression en lowercase et sans les caracte res speciaux //w = new Object(); // hashtable, key=word, value = list of the index of the html files scriptLetterTab = new Scriptfirstchar(); // Array containing the first letter of each word to look for var wordsList = new Array(); // Array with the words to look for var finalWordsList = new Array(); // Array with the words to look for after removing spaces var linkTab = new Array(); var fileAndWordList = new Array(); var txt_wordsnotfound = ""; // -------------------------------------- // Begin Thu's patch /*nqu: expressionInput, la recherche est lower cased, plus remplacement des char speciaux*/ //The original replacement expression is: //searchFor = expressionInput.toLowerCase().replace(/<\//g, "_st_").replace(/\$_/g, "_di_").replace(/\.|%2C|%3B|%21|%3A|@|\/|\*/g, " ").replace(/(%20)+/g, " ").replace(/_st_/g, "</").replace(/_di_/g, "%24_"); //The above expression was error prone because it did not deal with words that have a . as part of the word correctly, for example, document.txt //Do not automatically replace a . with a space searchFor = expressionInput.toLowerCase().replace(/<\//g, "_st_").replace(/\$_/g, "_di_").replace(/%2C|%3B|%21|%3A|@|\/|\*/g, " ").replace(/(%20)+/g, " ").replace(/_st_/g, "</").replace(/_di_/g, "%24_"); //If it ends with a period, replace it with a space searchFor = searchFor.replace(/[.]$/,""); // End Thu's Patch // ------------------------------------------ searchFor = searchFor.replace(/ +/g, " "); searchFor = searchFor.replace(/ $/, "").replace(/^ /, ""); wordsList = searchFor.split(" "); wordsList.sort(); //set the tokenizing method useCJKTokenizing = typeof indexerLanguage != "undefined" && (indexerLanguage == "zh" || indexerLanguage == "ja" || indexerLanguage == "ko"); //If Lucene CJKTokenizer was used as the indexer, then useCJKTokenizing will be true. Else, do normal tokenizing. // 2-gram tokenizinghappens in CJKTokenizing, //If doStem then make tokenize with Stemmer var finalArray; if (doStem){ if(useCJKTokenizing){ finalWordsList = cjkTokenize(wordsList); finalArray = finalWordsList; } else { finalWordsList = tokenize(wordsList); finalArray = finalWordsList; } } else if(useCJKTokenizing){ finalWordsList = cjkTokenize(wordsList); finalArray = finalWordsList; } else{ //load the scripts with the indices: the following lines do not work on the server. To be corrected /*if (IEBrowser) { scriptsarray = loadTheIndexScripts (scriptLetterTab); } */ /** * Compare with the indexed words (in the w[] array), and push words that are in it to tempTab. */ var tempTab = new Array(); // --------------------------------------- // Thu's patch //Do not use associative array in for loop, for example: //for(var t in finalWordsList) //it causes errors when finalWordList contains //stemmed words such as: kei from the stemmed word: key for(var t=0;t<finalWordsList.length;++t){ var aWord=finalWordsList[t]; //w is a Map like Object, use the current word in finalWordList as the key if(w[aWord] == undefined){ txt_wordsnotfound += aWord + " "; } else{ tempTab.push(aWord); } } finalWordsList = tempTab; //Check all the inputs to see if the root words are in the finalWordsList, if not add them there var inputs = expressionInput.split(' '); // Thu's Patch // ------------------------------------------- txt_wordsnotfound = expressionInput; finalWordsList = removeDuplicate(finalWordsList); } if (finalWordsList.length) { //search 'and' and 'or' one time fileAndWordList = SortResults(finalWordsList); if (fileAndWordList == undefined){ var cpt = 0; } else { var cpt = fileAndWordList.length; var maxNumberOfWords = fileAndWordList[0][0].motsnb; } if (cpt > 0){ var searchedWords = noWords.length; var foundedWords = fileAndWordList[0][0].motslisteDisplay.split(",").length; //console.info("search : " + noWords.length + " found : " + fileAndWordList[0][0].motslisteDisplay.split(",").length); if (searchedWords != foundedWords){ linkTab.push(partialSearch); } } for (var i = 0; i < cpt; i++) { var hundredProcent = fileAndWordList[i][0].scoring + 100 * fileAndWordList[i][0].motsnb; var ttScore_first = fileAndWordList[i][0].scoring; var numberOfWords = fileAndWordList[i][0].motsnb; if (fileAndWordList[i] != undefined) { linkTab.push("<p>" + txt_results_for + " " + "<span class=\"searchExpression\">" + fileAndWordList[i][0].motslisteDisplay + "</span>" + "</p>"); linkTab.push("<ul class='searchresult'>"); for (t in fileAndWordList[i]) { //linkTab.push("<li><a href=\"../"+fl[fileAndWordList[i][t].filenb]+"\">"+fl[fileAndWordList[i][t].filenb]+"</a></li>"); var ttInfo = fileAndWordList[i][t].filenb; // Get scoring var ttScore = fileAndWordList[i][t].scoring; var tempInfo = fil[ttInfo]; var pos1 = tempInfo.indexOf("@@@"); var pos2 = tempInfo.lastIndexOf("@@@"); var tempPath = tempInfo.substring(0, pos1); var tempTitle = tempInfo.substring(pos1 + 3, pos2); var tempShortdesc = tempInfo.substring(pos2 + 3, tempInfo.length); // toc.html will not be displayed on search result if (tempPath == 'toc.html'){ continue; } /* //file:///home/kasun/docbook/WEBHELP/webhelp-draft-output-format-idea/src/main/resources/web/webhelp/installation.html var linkString = "<li><a href=" + tempPath + ">" + tempTitle + "</a>"; // var linkString = "<li><a href=\"installation.html\">" + tempTitle + "</a>"; */ var split = fileAndWordList[i][t].motsliste.split(","); // var splitedValues = expressionInput.split(" "); // var finalArray = split.concat(splitedValues); arrayString = 'Array('; for(var x in finalArray){ if (finalArray[x].length > 2 || useCJKTokenizing){ arrayString+= "'" + finalArray[x] + "',"; } } arrayString = arrayString.substring(0,arrayString.length - 1) + ")"; var idLink = 'foundLink' + no; var linkString = '<li><a id="' + idLink + '" href="' + tempPath + '" class="foundResult">' + tempTitle + '</a>'; var starWidth = (ttScore * 100/ hundredProcent)/(ttScore_first/hundredProcent) * (numberOfWords/maxNumberOfWords); starWidth = starWidth < 10 ? (starWidth + 5) : starWidth; // Keep the 5 stars format if (starWidth > 85){ starWidth = 85; } /* var noFullStars = Math.ceil(starWidth/17); var fullStar = "curr"; var emptyStar = ""; if (starWidth % 17 == 0){ // am stea plina } else { } console.info(noFullStars); */ // Also check if we have a valid description if ((tempShortdesc != "null" && tempShortdesc != '...')) { linkString += "\n<div class=\"shortdesclink\">" + tempShortdesc + "</div>"; } linkString += "</li>"; // Add rating values for scoring at the list of matches linkString += "<div id=\"rightDiv\">"; linkString += "<div id=\"star\">"; //linkString += "<div style=\"color: rgb(136, 136, 136);\" id=\"starUser0\" class=\"user\">" // + ((ttScore * 100/ hundredProcent)/(ttScore_first/hundredProcent)) * 1 + "</div>"; linkString += "<ul id=\"star0\" class=\"star\">"; linkString += "<li id=\"starCur0\" class=\"curr\" style=\"width: " + starWidth + "px;\"></li>"; linkString += "</ul>"; linkString += "<br style=\"clear: both;\">"; linkString += "</div>"; linkString += "</div>"; //linkString += '<b>Rating: ' + ttScore + '</b>'; linkTab.push(linkString); no++; } linkTab.push("</ul>"); } } } var results = ""; if (linkTab.length > 0) { /*writeln ("<p>" + txt_results_for + " " + "<span class=\"searchExpression\">" + cleanwordsList + "</span>" + "<br/>"+"</p>");*/ results = "<p>"; //write("<ul class='searchresult'>"); for (t in linkTab) { results += linkTab[t].toString(); } results += "</p>"; } else { results = "<p>" + localeresource.search_no_results + " <span class=\"searchExpression\">" + txt_wordsnotfound + "</span>" + "</p>"; } // Verify if the browser is Google Chrome and the WebHelp is used on a local machine // If browser is Google Chrome and WebHelp is used on a local machine a warning message will appear // Highlighting will not work in this conditions. There is 2 workarounds if (verifyBrowser()){ document.getElementById('searchResults').innerHTML = results; } else { document.getElementById('searchResults').innerHTML = warningMsg + results; } } // Verify if the stemmed word is aproximately the same as the searched word function verifyWord(word, arr){ for (var i = 0 ; i < arr.length ; i++){ if (word[0] == arr[i][0] && word[1] == arr[i][1] //&& word[2] == arr[i][2] ){ return true; } } return false; } // Look for elements that start with searchedValue. function wordsStartsWith(searchedValue){ var toReturn = ''; for (var sv in w){ if (searchedValue.length < 3){ continue; } else { if (sv.toLowerCase().indexOf(searchedValue.toLowerCase()) == 0){ toReturn+=sv + ","; } } } return toReturn.length > 0 ? toReturn : undefined; } function tokenize(wordsList){ var stemmedWordsList = new Array(); // Array with the words to look for after removing spaces var cleanwordsList = new Array(); // Array with the words to look for // ------------------------------------------------- // Thu's patch for(var j=0;j<wordsList.length;++j){ var word = wordsList[j]; var originalWord=word; if(typeof stemmer != "undefined" ){ var stemmedWord=stemmer(word); if(w[stemmedWord]!=undefined){ stemQueryMap[stemmer(word)] = word; } else{ stemQueryMap[originalWord]=originalWord; } } else { if(w[word]!=undefined){ stemQueryMap[word] = word; } else{ stemQueryMap[originalWord]=originalWord; } } } //stemmedWordsList is the stemmed list of words separated by spaces. for (var t=0;t<wordsList.length;++t) { wordsList[t] = wordsList[t].replace(/(%22)|^-/g, ""); if (wordsList[t] != "%20") { scriptLetterTab.add(wordsList[t].charAt(0)); cleanwordsList.push(wordsList[t]); } } if(typeof stemmer != "undefined" ){ //Do the stemming using Porter's stemming algorithm for (var i = 0; i < cleanwordsList.length; i++) { var stemWord = stemmer(cleanwordsList[i]); if(w[stemWord]!=undefined){ stemmedWordsList.push(stemWord); } else{ stemmedWordsList.push(cleanwordsList[i]); } } // End Thu's patch // ------------------------------------------- } else { stemmedWordsList = cleanwordsList; } return stemmedWordsList; } //Invoker of CJKTokenizer class methods. function cjkTokenize(wordsList){ var allTokens= new Array(); var notCJKTokens= new Array(); var j=0; for(j=0;j<wordsList.length;j++){ var word = wordsList[j]; if(getAvgAsciiValue(word) < 127){ notCJKTokens.push(word); } else { var tokenizer = new CJKTokenizer(word); var tokensTmp = tokenizer.getAllTokens(); allTokens = allTokens.concat(tokensTmp); } } allTokens = allTokens.concat(tokenize(notCJKTokens)); return allTokens; } //A simple way to determine whether the query is in english or not. function getAvgAsciiValue(word){ var tmp = 0; var num = word.length < 5 ? word.length:5; for(var i=0;i<num;i++){ if(i==5) break; tmp += word.charCodeAt(i); } return tmp/num; } //CJKTokenizer function CJKTokenizer(input){ this.input = input; this.offset=-1; this.tokens = new Array(); this.incrementToken = incrementToken; this.tokenize = tokenize; this.getAllTokens = getAllTokens; this.unique = unique; function incrementToken(){ if(this.input.length - 2 <= this.offset){ // console.log("false "+offset); return false; } else { this.offset+=1; return true; } } function tokenize(){ //document.getElementById("content").innerHTML += x.substring(offset,offset+2)+"<br>"; return this.input.substring(this.offset,this.offset+2); } function getAllTokens(){ while(this.incrementToken()){ var tmp = this.tokenize(); this.tokens.push(tmp); } return this.unique(this.tokens); // document.getElementById("content").innerHTML += tokens+" "; // document.getElementById("content").innerHTML += "<br>dada"+sortedTokens+" "; // console.log(tokens.length+"dsdsds"); /*for(i=0;i<tokens.length;i++){ console.log(tokens[i]); var ss = tokens[i] == sortedTokens[i]; // document.getElementById("content").innerHTML += "<br>dada"+un[i]+"- "+stems[i]+"&nbsp;&nbsp;&nbsp;"+ ss; document.getElementById("content").innerHTML += "<br>"+sortedTokens[i]; }*/ } function unique(a) { var r = new Array(); o:for(var i = 0, n = a.length; i < n; i++) { for(var x = 0, y = r.length; x < y; x++) { if(r[x]==a[i]) continue o; } r[r.length] = a[i]; } return r; } } /* Scriptfirstchar: to gather the first letter of index js files to upload */ function Scriptfirstchar() { this.strLetters = ""; this.add = addLettre; } function addLettre(caract) { if (this.strLetters == 'undefined') { this.strLetters = caract; } else if (this.strLetters.indexOf(caract) < 0) { this.strLetters += caract; } return 0; } /* end of scriptfirstchar */ /*main loader function*/ /*tab contains the first letters of each word looked for*/ function loadTheIndexScripts(tab) { //alert (tab.strLetters); var scriptsarray = new Array(); for (var i = 0; i < tab.strLetters.length; i++) { scriptsarray[i] = "..\/search" + "\/" + tab.strLetters.charAt(i) + ".js"; } // add the list of html files i++; scriptsarray[i] = "..\/search" + "\/" + htmlfileList; //debug for (var t in scriptsarray) { //alert (scriptsarray[t]); } tab = new ScriptLoader(); for (t in scriptsarray) { tab.add(scriptsarray[t]); } tab.load(); //alert ("scripts loaded"); return (scriptsarray); } /* ScriptLoader: to load the scripts and wait that it's finished */ function ScriptLoader() { this.cpt = 0; this.scriptTab = new Array(); this.add = addAScriptInTheList; this.load = loadTheScripts; this.onScriptLoaded = onScriptLoadedFunc; } function addAScriptInTheList(scriptPath) { this.scriptTab.push(scriptPath); } function loadTheScripts() { var script; var head; head = document.getElementsByTagName('head').item(0); //script = document.createElement('script'); for (var el in this.scriptTab) { //alert (el+this.scriptTab[el]); script = document.createElement('script'); script.src = this.scriptTab[el]; script.type = 'text/javascript'; script.defer = false; head.appendChild(script); } } function onScriptLoadedFunc(e) { e = e || window.event; var target = e.target || e.srcElement; var isComplete = true; if (typeof target.readyState != undefined) { isComplete = (target.readyState == "complete" || target.readyState == "loaded"); } if (isComplete) { ScriptLoader.cpt++; if (ScriptLoader.cpt == ScriptLoader.scripts.length) { ScriptLoader.onLoadComplete(); } } } /* function onLoadComplete() { alert("loaded !!"); } */ /* End of scriptloader functions */ // Array.unique( strict ) - Remove duplicate values function unique(tab) { var a = new Array(); var i; var l = tab.length; if (tab[0] != undefined) { a[0] = tab[0]; } else { return -1; } for (i = 1; i < l; i++) { if (indexof(a, tab[i], 0) < 0) { a.push(tab[i]); } } return a; } function indexof(tab, element, begin) { for (var i = begin; i < tab.length; i++) { if (tab[i] == element) { return i; } } return -1; } /* end of Array functions */ /* Param: mots= list of words to look for. This function creates an hashtable: - The key is the index of a html file which contains a word to look for. - The value is the list of all words contained in the html file. Return value: the hashtable fileAndWordList */ function SortResults(mots) { var fileAndWordList = new Object(); if (mots.length == 0 || mots[0].length == 0) { return null; } // In generated js file we add scoring at the end of the word // Example word1*scoringForWord1,word2*scoringForWord2 and so on // Split after * to obtain the right values var scoringArr = Array(); for (var t in mots) { // get the list of the indices of the files. var listNumerosDesFicStr = w[mots[t].toString()]; if (listNumerosDesFicStr != undefined) { //alert ("listNumerosDesFicStr "+listNumerosDesFicStr); var tab = listNumerosDesFicStr.split(","); //for each file (file's index): for (var t2 in tab) { var tmp = ''; var idx = ''; var temp = tab[t2].toString(); if (temp.indexOf('*') != -1) { idx = temp.indexOf('*'); tmp = temp.substring(idx + 3, temp.length); temp = temp.substring(0, idx); } scoringArr.push(tmp); if (fileAndWordList[temp] == undefined) { fileAndWordList[temp] = "" + mots[t]; } else { fileAndWordList[temp] += "," + mots[t]; } //console.info("fileAndWordList[" + temp + "]=" + fileAndWordList[temp] + " : " + tmp); } } } var fileAndWordListValuesOnly = new Array(); // sort results according to values var temptab = new Array(); finalObj = new Array(); for (t in fileAndWordList) { finalObj.push(new newObj(t,fileAndWordList[t])); } if ( finalObj.length == 0 ) { // None of the queried words are not in the index (stemmed or not) return null; } finalObj = removeDerivates(finalObj); for (t in finalObj) { tab = finalObj[t].wordList.split(','); var tempDisplay = new Array(); for (var x in tab) { if(stemQueryMap[tab[x]] != undefined && doStem){ tempDisplay.push(stemQueryMap[tab[x]]); //get the original word from the stem word. } else { tempDisplay.push(tab[x]); //no stem is available. (probably a CJK language) } } var tempDispString = tempDisplay.join(", "); var index; for (x in fileAndWordList) { if (x === finalObj[t].filesNo) { index = x; break; } } var scoring = findRating(fileAndWordList[index], index); temptab.push(new resultPerFile(finalObj[t].filesNo, finalObj[t].wordList, tab.length, tempDispString, scoring)); fileAndWordListValuesOnly.push(finalObj[t].wordList); } fileAndWordListValuesOnly = unique(fileAndWordListValuesOnly); fileAndWordListValuesOnly = fileAndWordListValuesOnly.sort(compare_nbMots); var listToOutput = new Array(); for (var fawlvoIdx in fileAndWordListValuesOnly) { for (t in temptab) { if (temptab[t].motsliste == fileAndWordListValuesOnly[fawlvoIdx]) { if (listToOutput[fawlvoIdx] == undefined) { listToOutput[fawlvoIdx] = new Array(temptab[t]); } else { listToOutput[fawlvoIdx].push(temptab[t]); } } } } // Sort results by scoring, descending on the same group for (var ltoIdx in listToOutput) { listToOutput[ltoIdx].sort(function(a, b){ return b.scoring - a.scoring; }); } // If we have groups with same number of words, // will sort groups by higher scoring of each group for (var i = 0; i < listToOutput.length - 1; i++) { for (var j = i + 1; j < listToOutput.length; j++) { if (listToOutput[i][0].motsnb < listToOutput[j][0].motsnb || (listToOutput[i][0].motsnb == listToOutput[j][0].motsnb && listToOutput[i][0].scoring < listToOutput[j][0].scoring) ) { var x = listToOutput[i]; listToOutput[i] = listToOutput[j]; listToOutput[j] = x; } } } return listToOutput; } // Remove derivates words from the list of words function removeDerivates(obj){ var toResultObject = new Array(); for (i in obj){ var filesNo = obj[i].filesNo; var wordList = obj[i].wordList; var wList = wordList.split(","); var searchedWords = searchTextField.toLowerCase().split(" "); for (var k = 0 ; k < searchedWords.length ; k++){ for (var j = 0 ; j < wList.length ; j++){ if (wList[j].startsWith(searchedWords[k])){ wList[j] = searchedWords[k]; } } } wList = removeDuplicate(wList); var recreateList = ''; for(var x in wList){ recreateList+=wList[x] + ","; } recreateList = recreateList.substr(0, recreateList.length - 1); toResultObject.push(new newObj(filesNo, recreateList)); } return toResultObject; } function newObj(filesNo, wordList){ this.filesNo = filesNo; this.wordList = wordList; } // Add a new parameter. Scoring. function resultPerFile(filenb, motsliste, motsnb, motslisteDisplay, scoring, group) { //10 - spring,time - 2 - spring, time - 55 - 3 this.filenb = filenb; this.motsliste = motsliste; this.motsnb = motsnb; this.motslisteDisplay= motslisteDisplay; this.scoring = scoring; } function findRating(words, nr){ var sum = 0; var xx = words.split(','); for (jj = 0 ; jj < xx.length ; jj++){ var wrd = w[xx[jj]].split(','); for (var ii = 0 ; ii < wrd.length ; ii++){ var wrdno = wrd[ii].split('*'); if (wrdno[0] == nr){ sum+=parseInt(wrdno[1]); } } } return sum; } function compare_nbMots(s1, s2) { var t1 = s1.split(','); var t2 = s2.split(','); //alert ("s1:"+t1.length + " " +t2.length) if (t1.length == t2.length) { return 0; } else if (t1.length > t2.length) { return 1; } else { return -1; } //return t1.length - t2.length); } // return false if browser is Google Chrome and WebHelp is used on a local machine, not a web server function verifyBrowser(){ var returnedValue = true; var browser = BrowserDetect.browser; var addressBar = window.location.href; if (browser == 'Chrome' && addressBar.indexOf('file://') === 0){ returnedValue = false; } return returnedValue; } // Remove duplicate values from an array function removeDuplicate(arr) { var r = new Array(); o:for(var i = 0, n = arr.length; i < n; i++) { for(var x = 0, y = r.length; x < y; x++) { if(r[x]==arr[i]) continue o; } r[r.length] = arr[i]; } return r; } // Create startsWith method String.prototype.startsWith = function(str) { return (this.match("^"+str)==str); } function trim(str, chars) { return ltrim(rtrim(str, chars), chars); } function ltrim(str, chars) { chars = chars || "\\s"; return str.replace(new RegExp("^[" + chars + "]+", "g"), ""); } function rtrim(str, chars) { chars = chars || "\\s"; return str.replace(new RegExp("[" + chars + "]+$", "g"), ""); }
src/containers/__tests__/Collapsible-test.js
qingweibinary/binary-next-gen
import React from 'react'; import { expect } from 'chai'; import { createRenderer } from 'react-addons-test-utils'; import Collapsible from '../Collapsible'; describe('<Collapsible />', () => { it('should render the same component as the Collapsible component', () => { const renderer = createRenderer(); renderer.render(<Collapsible title="title">Hello</Collapsible>); const actualElement = renderer.getRenderOutput(); const expectedElement = ( <details> <summary>title</summary> Hello </details> ); expect(expectedElement).to.deep.equal(actualElement); }); });
lib/overlay.js
zeeskhan1990/react-native-option-select
import React, { Component } from 'react'; import { Dimensions, StyleSheet, TouchableWithoutFeedback, View, } from 'react-native'; const window = Dimensions.get('window'); const styles = StyleSheet.create({ container: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }, overlay: { position: 'absolute', width: window.width, height: window.height, flex : 1, justifyContent : "center", alignItems : "center", backgroundColor : "#ffffff" } }); class Overlay extends Component { constructor(props) { super(props); } render() { let { pageX, pageY, show, onPress, overlayStyles } = this.props; if (!show) { return null } return ( <TouchableWithoutFeedback style={styles.container} onPress={onPress}> <View style={[styles.overlay, { top: -pageY, left: -pageX }, overlayStyles]}> {this.props.children} </View> </TouchableWithoutFeedback> ); } } Overlay.propTypes = { pageX: React.PropTypes.number, pageY: React.PropTypes.number, show: React.PropTypes.bool, overlayStyles : React.PropTypes.object }; Overlay.defaultProps = { pageX: 0, pageY: 0, show: false, overlayStyles : {} }; module.exports = Overlay;
tech_stack/src/components/LibraryList.js
victorditadi/IQApp
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { ListView } from 'react-native'; import ListItem from './ListItem'; class LibraryList extends Component { componentWillMount(){ const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.dataSource = ds.cloneWithRows(this.props.libraries); } renderRow(library) { return <ListItem library={library} />; } render() { return ( <ListView dataSource={this.dataSource} renderRow={this.renderRow} /> ); } } const mapStateToProps = state => { return { libraries: state.libraries }; } export default connect(mapStateToProps)(LibraryList);
app/components/my_garden.js
bdunams/neo-veg
// Import React import React, { Component } from 'react'; import axios from 'axios'; import Calendar from './calendar'; // Helper Functions import Helpers from './utils/helpers.js'; // This is the Main component. export default class MyGarden extends Component{ constructor(props){ super(props) this.state = {myVegetablesList: [], gardenData: ""}; this.handleRemoveFromGarden = this.handleRemoveFromGarden.bind(this); } handleRemoveFromGarden(event){ event.preventDefault(); axios.post('/api/remove-from-garden', {vegId: event.target._id.value}) .then((data) => { if(data){ this.loadVegetables(); } } ); } loadVegetables(){ axios.get('/api/user-veg').then((response) => { let gardenData = response.data.Garden; if(gardenData){ let vegetables = gardenData.map((vegetable) => { let imageUrl = `images/${vegetable.VegName}.jpg`; if ( (! vegetable.IndoorSeedStart) || vegetable.IndoorStart === "FALSE" ) { var IndoorStart = "--"; var IndoorEnd = "--"; } else { var IndoorStart = moment(vegetable.IndoorSeedStart).format("MMMM DD"); var IndoorEnd = moment(vegetable.IndoorSeedEnd).format("MMMM DD"); } var OutdoorStart = moment(vegetable.OutdoorSeedStart).format("MMMM DD"); var OutdoorEnd = moment(vegetable.OutdoorSeedEnd).format("MMMM DD"); var HarvestStart = moment(vegetable.HarvestStart).format("MMMM DD"); var HarvestEnd = moment(vegetable.HarvestEnd).format("MMMM DD"); return( // <Vegetable id={vegetable.id} image={vegetable.image} > <div key={vegetable._id} id="vegCard" className="col-md-4"> <img src={imageUrl} className="img-responsive2" /> <h3>{vegetable.VegName}</h3> <h4>--Tips--</h4> <p>Spacing: {vegetable.Spacing}"</p> <p>Depth: {vegetable.Depth}"</p> <p>Fertilize: {vegetable.Fertilize}</p> <p>Water: {vegetable.Water}</p> <h4>--Important Dates--</h4> <p> Indoor Seeding: From {IndoorStart} to {IndoorEnd} </p> <p> Outdoor Planting/Seeding: From {OutdoorStart} to {OutdoorEnd} </p> <p> Harvest Time: From {HarvestStart} to {HarvestEnd} </p> <form method="post" onSubmit={this.handleRemoveFromGarden.bind(this)}> <input type="hidden" name="_id" value={vegetable._id} /> <button type="submit" className="btn btn-danger imageButtonNegative">x</button> </form> <hr /> </div> ) }) this.setState({ myVegetablesList: vegetables, gardenData: gardenData }); } }) } // Will run right before mounting component componentWillMount(){ this.loadVegetables(); } // Render Component render() { // IF the user has vegetables in their garden to display if(this.state.myVegetablesList.length > 0){ return ( <div> <Calendar gardenData={ this.state.gardenData } /> <div id="my-garden" className="container"> <div className="row"> {this.state.myVegetablesList} </div> </div> </div> ); } return ( <div id="my-garden" className="row"> <div className="container"> <h2>View your garden here!</h2> <p>You don't have any plants yet, go add some and track their progress!</p> </div> </div> ); } };
ajax/libs/rxjs/2.2.26/rx.compat.js
RNELord/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 = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new Error('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an iterable into an Observable sequence * * @example * var res = Rx.Observable.fromIterable(new Map()); * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. */ Observable.fromIterable = function (iterable, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var iterator; try { iterator = iterable[$iterator$](); } catch (e) { observer.onError(e); return; } return scheduler.scheduleRecursive(function (self) { var next; try { next = iterator.next(); } catch (err) { observer.onError(err); return; } if (next.done) { observer.onCompleted(); } else { observer.onNext(next.value); self(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * var res = observable.doAction(onNext, onError); * var res = observable.doAction(onNext, onError, onCompleted); * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(selector) { return this.map(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } function concatMapObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return concatMap.call(this, selector); } return concatMap.call(this, function () { return selector; }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function selectMany(selector) { return this.select(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } function selectManyObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.select(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** @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)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
src/decorators/withViewport.js
materliu/web-cache-speech-auxiliary-program
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); // eslint-disable-line react/no-set-state } }; } export default withViewport;
assets/global/plugins/highcharts/js/highcharts.src.js
creatindo/sim_sekolah
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v4.1.9 (2015-10-07) * * (c) 2009-2014 Torstein Honsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ /*jslint ass: true, sloppy: true, forin: true, plusplus: true, nomen: true, vars: true, regexp: true, newcap: true, browser: true, continue: true, white: true */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isMS = /(msie|trident|edge)/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = !isMS && /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isMS && !!doc.createElement('canvas').getContext, Renderer, hasTouch, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function pathAnim, timeUnits, noop = function () { return UNDEFINED; }, charts = [], chartCount = 0, PRODUCT = 'Highcharts', VERSION = '4.1.9', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', numRegex = /^[0-9]+$/, NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'], // Object for extending Axis AxisPlotLineOrBandExtension, // constants for attributes STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used Date, // Allow using a different Date class makeTime, timezoneOffset, getTimezoneOffset, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMilliseconds, setSeconds, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}, Highcharts; // The Highcharts namespace Highcharts = win.Highcharts = win.Highcharts ? error(16, true) : {}; Highcharts.seriesTypes = seriesTypes; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ var extend = Highcharts.extend = function (a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; }; /** * Deep merge two or more objects and return a third object. If the first argument is * true, the contents of the second object is copied into the first object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, args = arguments, len, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return obj && typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem.setAttribute(prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem.setAttribute(key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ var pick = Highcharts.pick = function () { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (arg !== UNDEFINED && arg !== null) { return arg; } } }; /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isMS && !hasSVG) { // #2686 if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () { return UNDEFINED; }; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Return a length based on either the integer value, or a percentage of a base. */ function relativeLength (value, base) { return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value); } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ var wrap = Highcharts.wrap = function (obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; }; function getTZOffset(timestamp) { return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return defaultOptions.lang.invalidDate || ''; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp - getTZOffset(timestamp)), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 'w': day, // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'k': hours, // Hours in 24h format, 0 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; if (val !== null) { val = Highcharts.numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) { var normalized, i, retInterval = interval; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { retInterval = multiples[i]; if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural (!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) { break; } } // multiply back to the correct magnitude retInterval *= magnitude; return retInterval; } /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ function error (code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } // else ... if (win.console) { console.log(msg); } } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num, prec) { return parseFloat( num.toPrecision(prec || 14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { chart.renderer.globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ timeUnits = { millisecond: 1, second: 1000, minute: 60000, hour: 3600000, day: 24 * 3600000, week: 7 * 24 * 3600000, month: 28 * 24 * 3600000, year: 364 * 24 * 3600000 }; /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ Highcharts.numberFormat = function (number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = +number || 0, c = decimals === -1 ? mathMin((n.toString().split('.')[1] || '').length, 20) : // Preserve decimals. Not huge numbers (#3793). (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(n).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return (s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : "")); }; /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams && start.length === end.length) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) { var obj = Fx.step, base; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && $.Tween) { // jQuery 1.8 model obj = $.Tween.propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { var elem; // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // Don't run animations on textual properties like align (#1821) if (fx.prop === 'align') { return; } // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+ wrap($.cssHooks.opacity, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) this.addAnimSetter('d', function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // Interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }); /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i, len = arr.length; for (i = 0; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Register Highcharts as a plugin in the respective framework */ $.fn.highcharts = function () { var constr = 'Chart', // default constructor args = arguments, options, ret, chart; if (this[0]) { if (isString(args[0])) { constr = args[0]; args = Array.prototype.slice.call(args, 1); } options = args[0]; // Create the chart if (options !== UNDEFINED) { /*jslint unused:false*/ options.chart = options.chart || {}; options.chart.renderTo = this[0]; chart = new Highcharts[constr](options, args[1]); ret = this; /*jslint unused:true*/ } // When called without parameters or with the return argument, get a predefined chart if (options === UNDEFINED) { ret = charts[attr(this[0], 'data-highcharts-chart')]; } } return ret; }; }, /** * Add an animation setter for a specific property */ addAnimSetter: function (prop, setter) { // jQuery 1.8 style if ($.Tween) { $.Tween.propHooks[prop] = { set: setter }; // pre 1.8 } else { $.fx.step[prop] = setter; } }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && el && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isMS && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; delete eventArguments.returnValue; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (!el.style) { el.style = {}; // #1881 } if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); if (params.opacity !== UNDEFINED && el.attr) { params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161) } el.hasAnim = 1; // #3342 $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy $(el).stop(); } } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = Highcharts.each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ defaultOptions = { colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // invalidDate: '', decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ' ' }, global: { useUTC: true, //timezoneOffset: 0, canvasToolsURL: 'http://code.highcharts.com/4.1.9/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/4.1.9/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 0, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, //style: { // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font // fontSize: '12px' //}, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#333333', fontSize: '18px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#555555' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, //linecap: 'round', lineWidth: 2, //shadow: false, // stacking: null, marker: { //enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true, lineWidthPlus: 1, radiusPlus: 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: { align: 'center', // defer: true, // enabled: false, formatter: function () { return this.y === null ? '' : Highcharts.numberFormat(this.y, -1); }, style: { color: 'contrast', fontSize: '11px', fontWeight: 'bold', textShadow: '0 0 6px contrast, 0 0 3px contrast' }, verticalAlign: 'bottom', // above singular point x: 0, y: 0, // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, padding: 5 // shadow: false }, cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series softThreshold: true, states: { // states for the entire series hover: { //enabled: false, lineWidthPlus: 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10, opacity: 0.25 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, //borderWidth: 0, borderColor: '#909090', borderRadius: 0, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 20, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { color: '#333333', fontSize: '12px', fontWeight: 'bold' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, // symbolRadius: 0, // symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '45%' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(249, 249, 249, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, footerFormat: '', //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', shadow: true, //shape: 'callout', //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', pointerEvents: 'none', // #1686 http://caniuse.com/#feat=pointer-events whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var globalOptions = defaultOptions.global, useUTC = globalOptions.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; Date = globalOptions.Date || window.Date; timezoneOffset = useUTC && globalOptions.timezoneOffset; getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset; makeTime = function (year, month, date, hours, minutes, seconds) { var d; if (useUTC) { d = Date.UTC.apply(0, arguments); d += getTZOffset(d); } else { d = new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); } return d; }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMilliseconds = SET + 'Milliseconds'; setSeconds = SET + 'Seconds'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Copy in the default options defaultOptions = merge(true, defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/, hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/; var Color = function (input) { // declare variables var rgba = [], result, stops; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // Gradients if (input && input.stops) { stops = map(input.stops, function (stop) { return Color(stop[1]); }); // Solid colors } else { // rgba result = rgbaRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = hexRegEx.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = rgbRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } } } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; if (stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (stops) { each(stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, rgba: rgba, setOpacity: setOpacity, raw: input }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { // Default base for animation opacity: 1, // For labels, these CSS properties are applied to the <text> node directly textProps: ['fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color', 'lineHeight', 'width', 'textDecoration', 'textOverflow', 'textShadow'], /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, this.renderer.globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions, {}); //#2625 if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params, null, complete); } return this; }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, radAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { radAttr = gradAttr; // Save the radial attributes for updating gradAttr = merge(gradAttr, renderer.getRadialAttr(radialReference, radAttr), { gradientUnits: 'userSpaceOnUse' } ); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); gradientObject.radAttr = radAttr; // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')'); elem.gradient = key; } }, /** * Apply a polyfill to the text-stroke CSS property, by copying the text element * and apply strokes to the copy. * * Contrast checks at http://jsfiddle.net/highcharts/43soe9m1/2/ * * docs: update default, document the polyfill and the limitations on hex colors and pixel values, document contrast pseudo-color */ applyTextShadow: function (textShadow) { var elem = this.element, tspans, hasContrast = textShadow.indexOf('contrast') !== -1, styles = {}, forExport = this.renderer.forExport, // IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check // this again with new IE release. In exports, the rendering is passed to PhantomJS. supports = forExport || (elem.style.textShadow !== UNDEFINED && !isMS); // When the text shadow is set to contrast, use dark stroke for light text and vice versa if (hasContrast) { styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill)); } // Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this, // it removes the text shadows. if (isWebKit || forExport) { styles.textRendering = 'geometricPrecision'; } /* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/) if (elem.textContent.indexOf('2.') === 0) { elem.style['text-shadow'] = 'none'; supports = false; } // */ // No reason to polyfill, we've got native support if (supports) { this.css(styles); // Apply altered textShadow or textRendering workaround } else { this.fakeTS = true; // Fake text shadow // In order to get the right y position of the clones, // copy over the y setter this.ySetter = this.xSetter; tspans = [].slice.call(elem.getElementsByTagName('tspan')); each(textShadow.split(/\s?,\s?/g), function (textShadow) { var firstChild = elem.firstChild, color, strokeWidth; textShadow = textShadow.split(' '); color = textShadow[textShadow.length - 1]; // Approximately tune the settings to the text-shadow behaviour strokeWidth = textShadow[textShadow.length - 2]; if (strokeWidth) { each(tspans, function (tspan, y) { var clone; // Let the first line start at the correct X position if (y === 0) { tspan.setAttribute('x', elem.getAttribute('x')); y = elem.getAttribute('y'); tspan.setAttribute('y', y || 0); if (y === null) { elem.setAttribute('y', 0); } } // Create the clone and apply shadow properties clone = tspan.cloneNode(1); attr(clone, { 'class': PREFIX + 'text-shadow', 'fill': color, 'stroke': color, 'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3), 'stroke-width': strokeWidth, 'stroke-linejoin': 'round' }); elem.insertBefore(clone, firstChild); }); } }); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val, complete) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr; // single key-value pair if (typeof hash === 'string' && val !== UNDEFINED) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element); } // Let the shadow follow the main element if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { this.updateShadows(key, value); } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } // In accordance with animate, run a complete callback if (complete) { complete(); } return ret; }, updateShadows: function (key, value) { var shadows = this.shadows, i = shadows.length; while (i--) { shadows[i].setAttribute( key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value ); } }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (rect) { var wrapper = this, key, attribs = {}, normalizer, strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer; rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer; rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer); rect.strokeWidth = strokeWidth; for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = (styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) || elemWrapper.textWidth; // #3501 // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) { delete styles.width; } // serialize and set style attribute if (isMS && !hasSVG) { css(elemWrapper.element, styles); } else { /*jslint unparam: true*/ hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { var existingGradient = this.renderer.gradients[this.element.gradient]; this.element.radialReference = coordinates; // On redrawing objects with an existing gradient, the gradient needs // to be repositioned (#3801) if (existingGradient && existingGradient.radAttr) { existingGradient.animate( this.renderer.getRadialAttr( coordinates, existingGradient.radAttr ) ); } return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, element = wrapper.element, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); // Delete bBox memo when the rotation changes //delete wrapper.bBox; } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function (reload) { var wrapper = this, bBox,// = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad, textStr = wrapper.textStr, textShadow, elemStyle = element.style, toggleTextShadowShim, cacheKey; if (textStr !== UNDEFINED) { // Properties that affect bounding box cacheKey = ['', rotation || 0, styles && styles.fontSize, element.style.width].join(','); // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. if (textStr === '' || numRegex.test(textStr)) { cacheKey = 'num:' + textStr.toString().length + cacheKey; // Caching all strings reduces rendering time by 4-5%. } else { cacheKey = textStr + cacheKey; } } if (cacheKey && !reload) { bBox = renderer.cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. // When the text shadow shim is used, we need to hide the fake shadows // to get the correct bounding box (#3872) toggleTextShadowShim = this.fakeTS && function (display) { each(element.querySelectorAll('.' + PREFIX + 'text-shadow'), function (tspan) { tspan.style.display = display; }); }; // Workaround for #3842, Firefox reporting wrong bounding box for shadows if (isFirefox && elemStyle.textShadow) { textShadow = elemStyle.textShadow; elemStyle.textShadow = ''; } else if (toggleTextShadowShim) { toggleTextShadowShim(NONE); } bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; // #3842 if (textShadow) { elemStyle.textShadow = textShadow; } else if (toggleTextShadowShim) { toggleTextShadowShim(''); } } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568) if (isMS && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } // Cache it if (cacheKey) { renderer.cache[cacheKey] = bBox; } } return bBox; }, /** * Show the element */ show: function (inherit) { return this.attr({ visibility: inherit ? 'inherit' : VISIBLE }); }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, element = this.element, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // Mark as added this.added = true; // If we're adding to renderer root, or other elements in the group // have a z index, we need to handle it if (!parent || parent.handleZ || this.zIndex) { inserted = this.zIndexSetter(); } // If zIndex is not handled, append at the end if (!inserted) { (parent ? parent.element : renderer.box).appendChild(element); } // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697). while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; }, xGetter: function (key) { if (this.element.nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function (key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, dashstyleSetter: function (value) { var i; value = value && value.toLowerCase(); if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * this['stroke-width']; } value = value.join(',') .replace('NaN', 'none'); // #3226 this.element.setAttribute('stroke-dasharray', value); } }, alignSetter: function (value) { this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]); }, opacitySetter: function (value, key, element) { this[key] = value; element.setAttribute(key, value); }, titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); this.element.appendChild(titleNode); } titleNode.appendChild( doc.createTextNode( (String(pick(value), '')).replace(/<[^>]*>/g, '') // #3276, #3895 ) ); }, textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, visibilitySetter: function (value, key, element) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881, #3909) if (value === 'inherit') { element.removeAttribute(key); } else { element.setAttribute(key, value); } }, zIndexSetter: function (value, key) { var renderer = this.renderer, parentGroup = this.parentGroup, parentWrapper = parentGroup || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, otherElement, otherZIndex, element = this.element, inserted, run = this.added, i; if (defined(value)) { element.setAttribute(key, value); // So we can read it for other elements in the group value = +value; if (this[key] === value) { // Only update when needed (#3865) run = false; } this[key] = value; } // Insert according to this and other elements' zIndex. Before .add() is called, // nothing is done. Then on add, or by later calls to zIndexSetter, the node // is placed on the right place in the DOM. if (run) { value = this.zIndex; if (value && parentGroup) { parentGroup.handleZ = true; } childNodes = parentNode.childNodes; for (i = 0; i < childNodes.length && !inserted; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // Insert before the first element with a higher zIndex pInt(otherZIndex) > value || // If no zIndex given, insert before the first element with a zIndex (!defined(value) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; } } if (!inserted) { parentNode.appendChild(element); } } return inserted; }, _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) { this[key] = value; this.doTransform = true; }; // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the // stroke attribute altogether. #1270, #1369, #3065, #3072. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (this.stroke && this['stroke-width']) { this.strokeWidth = this['stroke-width']; SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { element.removeAttribute('stroke'); this.hasStroke = false; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, style, forExport, allowHTML) { var renderer = this, loc = location, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }) .css(this.getStyle(style)); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.allowHTML = allowHTML; renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, getStyle: function (style) { return (this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, style)); }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Get converted radial gradient attributes */ getRadialAttr: function (radialReference, gradAttr) { return { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2] }; }, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, styleRegex, hrefRegex, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textShadow = textStyles && textStyles.textShadow, ellipsis = textStyles && textStyles.textOverflow === 'ellipsis', i = childNodes.length, tempParent = width && !wrapper.added && this.box, getLineHeight = function (tspan) { return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12), tspan ).h; }, unescapeAngleBrackets = function (inputStr) { return inputStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if (!hasMarkup && !textShadow && !ellipsis && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr))); return; // Complex strings, add more logic } else { styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (tempParent) { tempParent.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' '); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan) ); } /*if (width) { renderer.breakText(wrapper, width); }*/ // Check width and apply soft breaks or ellipsis if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'), tooLong, wasTooLong, actualWidth, rest = [], dy = getLineHeight(tspan), softLineNo = 1, rotation = wrapper.rotation, wordStr = span, // for ellipsis cursor = wordStr.length, // binary search cursor bBox; while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) { wrapper.rotation = 0; // discard rotation when computing box bBox = wrapper.getBBox(true); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!hasSVG && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; // For ellipsis, do a binary search for the correct string length if (wasTooLong === undefined) { wasTooLong = tooLong; // First time } if (ellipsis && wasTooLong) { cursor /= 2; if (wordStr === '' || (!tooLong && cursor < 0.5)) { words = []; // All ok, break out } else { if (tooLong) { wasTooLong = true; } wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor)); words = [wordStr + (width > 3 ? '\u2026' : '')]; tspan.removeChild(tspan.firstChild); } // Looping down, this is the first word sequence that is not too long, // so we can move on to build the next line. } else if (!tooLong || words.length === 1) { words = rest; rest = []; if (words.length) { softLineNo++; tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); } if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } if (wasTooLong) { wrapper.attr('title', wrapper.textStr); } wrapper.rotation = rotation; } spanNo++; } } }); }); if (tempParent) { tempParent.removeChild(textNode); // attach it to the DOM to read offset width } // Apply the text shadow if (textShadow && wrapper.applyTextShadow) { wrapper.applyTextShadow(textShadow); } } }, /* breakText: function (wrapper, width) { var bBox = wrapper.getBBox(), node = wrapper.element, textLength = node.textContent.length, pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width increment = 0, finalPos; if (bBox.width > width) { while (finalPos === undefined) { textLength = node.getSubStringLength(0, pos); if (textLength <= width) { if (increment === -1) { finalPos = pos; } else { increment = 1; } } else { if (increment === 1) { finalPos = pos - 1; } else { increment = -1; } } pos += increment; } } console.log(finalPos, node.getSubStringLength(0, finalPos)) }, */ /** * Returns white for dark colors and black for bright colors */ getContrast: function (color) { color = Color(color).rgba; return color[0] + color[1] + color[2] > 384 ? '#000000' : '#FFFFFF'; }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState.style; delete normalState.style; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState.style; delete hoverState.style; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState.style; delete pressedState.style; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState.style; delete disabledState.style; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function (e) { if (curState !== 3) { callback.call(label, e); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }, wrapper = this.createElement('circle'); wrapper.xSetter = function (value) { this.element.setAttribute('cx', value); }; wrapper.ySetter = function (value) { this.element.setAttribute('cy', value); }; return wrapper.attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === UNDEFINED ? {} : { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; if (strokeWidth !== UNDEFINED) { attribs.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } if (r) { attribs.r = r; } wrapper.rSetter = function (value) { attr(this.element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]); // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { // Special case for SVGs on IE11, the width is not accessible until the image is // part of the DOM (#2854). if (this.width === 0) { css(this, { position: ABSOLUTE, top: '-999em' }); document.body.appendChild(this); } // Center the image centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); // Clean up after #2854 workaround. if (this.parentNode) { this.parentNode.removeChild(this); } }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = mathMin((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; wrapper.count = 0; return wrapper; }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper, attr = {}; if (useHTML && (renderer.allowHTML || !renderer.forExport)) { return renderer.html(str, x, y); } attr.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attr.y = Math.round(y); } if (str || str === 0) { attr.text = str; } wrapper = renderer.createElement('text') .attr(attr); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } if (!useHTML) { wrapper.xSetter = function (value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize, elem) { var lineHeight, baseline, style; fontSize = fontSize || this.style.fontSize; if (!fontSize && elem && win.getComputedStyle) { elem = elem.element || elem; // SVGElement style = win.getComputedStyle(elem, ""); fontSize = style && style.fontSize; // #4309, the style doesn't exist inside a hidden iframe in Firefox } fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2); baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline, f: fontSize }; }, /** * Correct X and Y positioning of a label for rotation (#1764) */ rotCorr: function (baseline, rotation, alterY) { var y = baseline; if (rotation && alterY) { y = mathMax(y * mathCos(rotation * deg2rad), 4); } return { x: (-baseline / 3) * mathSin(rotation * deg2rad), y: y }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && defined(text.textStr) && text.getBBox(); //#3295 && 3514 box failure when string equals 0 wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding) + crispAdjust; boxY = (baseline ? -baselineOffset : 0) + crispAdjust; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); if (!box.isImg) { // #4324, fill "none" causes it to be ignored by mouse events in IE box.attr('fill', NONE); } box.add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(extend({ width: mathRound(wrapper.width), height: mathRound(wrapper.height) }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr('x', x); if (y !== UNDEFINED) { text.attr('y', y); } } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = value; }; wrapper.heightSetter = function (value) { height = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = wrapper.padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== UNDEFINED) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } crispAdjust = value % 2 / 2; boxAttr(key, value); }; wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key === 'fill' && value) { needsBox = true; } boxAttr(key, value); }; wrapper.anchorXSetter = function (value, key) { anchorX = value; boxAttr(key, mathRound(value) - crispAdjust - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + padding); } wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(wrapper.textProps, function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } if (styles && styles.textOverflow === 'ellipsis') { styles.whiteSpace = 'nowrap'; styles.overflow = 'hidden'; } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element; // faking getBBox in exported SVG in legacy IE // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } return { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], shadows = wrapper.shadows, styles = wrapper.styles; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth, wrapper.textAlign].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } width = pick(wrapper.elemWidth, elem.offsetWidth); // Update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: (styles && styles.whiteSpace) || 'normal' // #3331 }); width = textWidth; } wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + PX, top: (y + (wrapper.yCorr || 0)) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isMS ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function (width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer; // Text setter wrapper.textSetter = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; wrapper.htmlUpdateTransform(); }; // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, fontFamily: this.style.fontFamily, fontSize: this.style.fontSize }); // Keep the whiteSpace style outside the wrapper.styles collection element.style.whiteSpace = 'nowrap'; // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle, cls = attr(parentGroup.element, 'class'); if (cls) { cls = { className: cls }; } // else null // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, cls, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup, { translateXSetter: function (value, key) { htmlGroupStyle.left = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function (value, key) { htmlGroupStyle.top = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; } }); // These properties are set as attributes on the SVG group, and as // identical CSS properties on the div. (#3542) each(['opacity', 'visibility'], function (prop) { wrap(parentGroup, prop + 'Setter', function (proceed, value, key, elem) { proceed.call(this, value, key, elem); htmlGroupStyle[key] = value; }); }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; } }); /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks if (wrapper.onAdd) { wrapper.onAdd(); } return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function () { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = mathCos(rotation * deg2rad), sintheta = mathSin(rotation * deg2rad); css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Get the positioning correction for the span after rotating. */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? mathCos(rotation * deg2rad) : 1, sintheta = rotation ? mathSin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = costheta < 0 && -width; this.yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(this.element, { textAlign: align }); } }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract or // add 1 from the end X and Y positions. #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; }, updateShadows: noop, // Used in SVG only setAttr: function (key, value) { if (docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless set like this this.element.className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this[key] = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; this.d = value.join && value.join(' '); // used in getter for animation element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts rotationSetter: function (value, key, element) { var style = element.style; this[key] = style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; style.top = mathRound(mathCos(value * deg2rad)) + PX; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = VISIBLE; } // Let the shadow follow the main element if (this.shadows) { each(this.shadows, function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (element.nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { element.style[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; }/* else { value = mathMax(0, value); // don't set width or height below zero (#311) }*/ // clipping rectangle special if (this.updateClipping) { this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; } }; Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height, style) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV) .css(extend(this.getStyle(style), { position: RELATIVE})); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.cache = {}; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], count: 0, left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do. member.css(clipRect.getCSS(member)); } }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right wrapper.onAdd = applyRadialGradient; } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1), top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1), rotation: -90 }); // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806. each(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape. When borders are not rounded, * use the simpler square path, else use the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[ !defined(options) || !options.r ? 'square' : 'callout' ].call(0, x, y, w, h, options); } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return offsetWidth; }; /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS //css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; // first call if (!defined(label)) { tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) //.attr(attr) // without position absolute, IE export sometimes is wrong .css(merge(labelOptions.style)) .add(axis.labelGroup) : null; tick.labelLength = label && label.getBBox().width; // Un-rotated length tick.rotation = 0; // Base value to detect change for new calls to getBBox // update } else if (label) { label.attr({ text: str }); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { return this.label ? this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] : 0; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (xy) { var axis = this.axis, pxPos = xy.x, chartWidth = axis.chart.chartWidth, spacing = axis.chart.spacing, leftBound = pick(axis.labelLeft, mathMin(axis.pos, spacing[3])), rightBound = pick(axis.labelRight, mathMax(axis.pos + axis.len, chartWidth - spacing[1])), label = this.label, rotation = this.rotation, factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign], labelWidth = label.getBBox().width, slotWidth = axis.slotWidth, xCorrection = factor, goRight = 1, leftPos, rightPos, textWidth, css = {}; // Check if the label overshoots the chart spacing box. If it does, move it. // If it now overshoots the slotWidth, add ellipsis. if (!rotation) { leftPos = pxPos - factor * labelWidth; rightPos = pxPos + (1 - factor) * labelWidth; if (leftPos < leftBound) { slotWidth = xy.x + slotWidth * (1 - factor) - leftBound; } else if (rightPos > rightBound) { slotWidth = rightBound - xy.x + slotWidth * factor; goRight = -1; } slotWidth = mathMin(axis.slotWidth, slotWidth); // #4177 if (slotWidth < axis.slotWidth && axis.labelAlign === 'center') { xy.x += goRight * (axis.slotWidth - slotWidth - xCorrection * (axis.slotWidth - mathMin(labelWidth, slotWidth))); } // If the label width exceeds the available space, set a text width to be // picked up below. Also, if a width has been set before, we need to set a new // one because the reported labelWidth will be limited by the box (#3938). if (labelWidth > slotWidth || (axis.autoRotation && label.styles.width)) { textWidth = slotWidth; } // Add ellipsis to prevent rotated labels to be clipped against the edge of the chart } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) { textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound); } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) { textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad)); } if (textWidth) { css.width = textWidth; if (!axis.options.labels.style.textOverflow) { css.textOverflow = 'ellipsis'; } label.css(css); } }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines, rotCorr = axis.tickRotCorr || { x: 0, y: 0 }, yOffset = pick(labelOptions.y, rotCorr.y + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))), line; x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { line = (index / (step || 1) % staggerLines); y += line * (axis.labelOffset / staggerLines); } return { x: x, y: mathRound(y) }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = pick(options[tickPrefix + 'Width'], !type && axis.isXAxis ? 1 : 0), // X axis defaults to 1 tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = /*axis.labelStep || */labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 opacity = pick(opacity, 1); this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { tick.handleOverflow(xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ Highcharts.PlotLineOrBand = function (axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } }; Highcharts.PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs = {}, renderer = axis.chart.renderer; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band path = axis.getPlotBandPath(from, to, options); if (color) { attribs.fill = color; } if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function () { svgElem.show(); }; if (label) { plotLine.label = label = label.destroy(); } } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign : !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); // add the SVG element if (!label) { attribs = { align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation }; if (defined(zIndex)) { attribs.zIndex = zIndex; } plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr(attribs) .css(optionsLabel.style) .add(); } // get the bounding box and align the label // #3000 changed to better handle choice between plotband or plotline xs = [path[1], path[4], (isBand ? path[6] : path[1])]; ys = [path[2], path[5], (isBand ? path[7] : path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function () { // remove it from the lookup erase(this.axis.plotLinesAndBands, this); delete this.axis; destroyObjectProperties(this); } }; /** * Object with members for extending the Axis prototype */ AxisPlotLineOrBandExtension = { /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to, null, null, true), path = this.getPlotLinePath(from, null, null, true); if (path && toPath && path.toString() !== toPath.toString()) { // #3836 path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, addPlotBand: function (options) { return this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { return this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options, coll) { var obj = new Highcharts.PlotLineOrBand(this, options).render(), userOptions = this.userOptions; if (obj) { // #2189 // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); } return obj; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, options = this.options, userOptions = this.userOptions, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) { i = arr.length; while (i--) { if (arr[i].id === id) { erase(arr, arr[i]); } } }); } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ var Axis = Highcharts.Axis = function () { this.init.apply(this, arguments); }; Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#D8D8D8', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: { enabled: true, // rotation: 0, // align: 'center', // step: null, style: { color: '#606060', cursor: 'default', fontSize: '11px' }, x: 0, y: 15 /*formatter: function () { return this.value; },*/ }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 10, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', //tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#707070' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime //visible: true }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, //tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return Highcharts.numberFormat(this.total, -1); }, style: merge(defaultPlotOptions.line.dataLabels.style, { color: '#000000' }) } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -15, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { autoRotation: [-45], x: 0, y: null // based on font size // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for top axes */ defaultTopAxisOptions: { labels: { autoRotation: [-45], x: 0, y: -15 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; axis.chart = chart; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.coll = isXAxis ? 'xAxis' : 'yAxis'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.side || (axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3)); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; axis.reversed = options.reversed; axis.visible = options.visible !== false; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; axis.names = axis.names || []; // Preserve on update (#3830) // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; // Major ticks axis.ticks = {}; axis.labelEdge = []; // Minor ticks axis.minorTicks = {}; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; axis.stacksTouched = 0; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis && !this.isColorAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && (value * 10) % multi === 0 && numericSymbols[i] !== null) { ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (mathAbs(value) >= 10000) { // add thousands separators ret = Highcharts.numberFormat(value, -1); } else { // small numbers ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466 } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // Reset properties in case we're redrawing (#3353) axis.dataMin = axis.dataMax = axis.threshold = null; axis.softThreshold = !axis.isXAxis; if (axis.buildStacks) { axis.buildStacks(); } // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { axis.threshold = threshold; } // If any series has a hard threshold, it takes precedence if (!seriesOptions.softThreshold || axis.isLog) { axis.softThreshold = false; } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this.linkedParent || this, // #1417 sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, doPostTranslate = (axis.doPostTranslate || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (doPostTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (doPostTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB, /** * Check if x is between a and b. If not, either move to a/b or skip, * depending on the force parameter. */ between = function (x, a, b) { if (x < a || x > b) { if (force) { x = mathMin(mathMax(a, x), b); } else { skip = true; } } return x; }; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; x1 = x2 = between(x1, axisLeft, axisLeft + axis.width); } else { x1 = axisLeft; x2 = cWidth - axis.right; y1 = y2 = between(y1, axisTop, axisTop + axis.height); } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1); }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, pointRangePadding = axis.pointRangePadding || 0, min = axis.min - pointRangePadding, // #1498 max = axis.max + pointRangePadding, // #1498 range = max - min, len; // If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them. if (range && range / minorTickInterval < axis.len / 3) { // #3875 if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( axis.getTimeTicks( axis.normalizeTimeTickInterval(minorTickInterval), min, max, options.startOfWeek ) ); } else { for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) { minorTickPositions.push(pos); } } } if(minorTickPositions.length !== 0) { // don't change the extremes, when there is no minor ticks axis.trimTicks(minorTickPositions, options.startOnTick, options.endOnTick); // #3652 #3743 #1498 } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs, minRange; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA, isXAxis = axis.isXAxis; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = hasCategories ? 1 : (isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806 pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; pointRange = mathMax(pointRange, seriesPointRange); if (!axis.single) { // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); } // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value if (isXAxis) { axis.closestPointRange = closestPointRange; } } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, minFromRange: function () { return this.max - this.range; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickInterval: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, categories = axis.categories, threshold = axis.threshold, softThreshold = axis.softThreshold, thresholdMin, thresholdMax, hardMin, hardMax; if (!isDatetimeAxis && !categories && !isLinked) { this.getTickAmount(); } // Min or max set either by zooming/setExtremes or initial options hardMin = pick(axis.userMin, options.min); hardMax = pick(axis.userMax, options.max); // Linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[axis.coll][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } // Initial min and max from the extreme data values } else { // Adjust to hard threshold if (!softThreshold && defined(threshold)) { if (axis.dataMin >= threshold) { thresholdMin = threshold; minPadding = 0; } else if (axis.dataMax <= threshold) { thresholdMax = threshold; maxPadding = 0; } } axis.min = pick(hardMin, thresholdMin, axis.dataMin); axis.max = pick(hardMax, thresholdMax, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } // The correctFloat cures #934, float errors on full tens. But it // was too aggressive for #4360 because of conversion back to lin, // therefore use precision 15. axis.min = correctFloat(log2lin(axis.min), 15); axis.max = correctFloat(log2lin(axis.max), 15); } // handle zoomed range if (axis.range && defined(axis.max)) { axis.userMin = axis.min = hardMin = mathMax(axis.min, axis.minFromRange()); // #618 axis.userMax = hardMax = axis.max; axis.range = null; // don't use it when running setExtremes } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(hardMin) && minPadding) { axis.min -= length * minPadding; } if (!defined(hardMax) && maxPadding) { axis.max += length * maxPadding; } } } // Stay within floor and ceiling if (isNumber(options.floor)) { axis.min = mathMax(axis.min, options.floor); } if (isNumber(options.ceiling)) { axis.max = mathMin(axis.max, options.ceiling); } // When the threshold is soft, adjust the extreme value only if // the data extreme and the padded extreme land on either side of the threshold. For example, // a series of [0, 1, 2, 3] would make the yAxis add a tick for -1 because of the // default minPadding and startOnTick options. This is prevented by the softThreshold // option. if (softThreshold && defined(axis.dataMin)) { threshold = threshold || 0; if (!defined(hardMin) && axis.min < threshold && axis.dataMin >= threshold) { axis.min = threshold; } else if (!defined(hardMax) && axis.max > threshold && axis.dataMax <= threshold) { axis.max = threshold; } } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943) if (axis.pointRange) { axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange); if (!tickIntervalOption && axis.tickInterval < minTickInterval) { axis.tickInterval = minTickInterval; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog && !tickIntervalOption) { axis.tickInterval = normalizeTickInterval( axis.tickInterval, null, getMagnitude(axis.tickInterval), // If the tick interval is between 0.5 and 5 and the axis max is in the order of // thousands, chances are we are dealing with years. Don't allow decimals. #3363. pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)), !!this.tickAmount ); } // Prevent ticks from getting so close that we can't draw the labels if (!this.tickAmount && this.len) { // Color axis with disabled legend has no length axis.tickInterval = axis.unsquish(); } this.setTickPositions(); }, /** * Now we have computed the normalized tickInterval, get the tick positions */ setTickPositions: function () { var options = this.options, tickPositions, tickPositionsOption = options.tickPositions, tickPositioner = options.tickPositioner, startOnTick = options.startOnTick, endOnTick = options.endOnTick, single; // Set the tickmarkOffset this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' && this.tickInterval === 1) ? 0.5 : 0; // #3202 // get minorTickInterval this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ? this.tickInterval / 5 : options.minorTickInterval; // Find the tick positions this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565) if (!tickPositions) { if (this.isDatetimeAxis) { tickPositions = this.getTimeTicks( this.normalizeTimeTickInterval(this.tickInterval, options.units), this.min, this.max, options.startOfWeek, this.ordinalPositions, this.closestPointRange, true ); } else if (this.isLog) { tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max); } else { tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max); } // Too dense ticks, keep only the first and last (#4477) if (tickPositions.length > this.len) { tickPositions = [tickPositions[0], tickPositions.pop()]; } this.tickPositions = tickPositions; // Run the tick positioner callback, that allows modifying auto tick positions. if (tickPositioner) { tickPositioner = tickPositioner.apply(this, [this.min, this.max]); if (tickPositioner) { this.tickPositions = tickPositions = tickPositioner; } } } if (!this.isLinked) { // reset min/max or remove extremes based on start/end on tick this.trimTicks(tickPositions, startOnTick, endOnTick); // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (this.min === this.max && defined(this.min) && !this.tickAmount) { // Substract half a unit (#2619, #2846, #2515, #3390) single = true; this.min -= 0.5; this.max += 0.5; } this.single = single; if (!tickPositionsOption && !tickPositioner) { this.adjustTickAmount(); } } }, /** * Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max */ trimTicks: function (tickPositions, startOnTick, endOnTick) { var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = this.minPointOffset || 0; if (startOnTick) { this.min = roundedMin; } else if (this.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (endOnTick) { this.max = roundedMax; } else if (this.max + minPointOffset < roundedMax) { tickPositions.pop(); } // If no tick are left, set one tick in the middle (#3195) if (tickPositions.length === 0 && defined(roundedMin)) { tickPositions.push((roundedMax + roundedMin) / 2); } }, /** * Set the max ticks of either the x and y axis collection */ getTickAmount: function () { var others = {}, // Whether there is another axis to pair with this one hasOther, options = this.options, tickAmount = options.tickAmount, tickPixelInterval = options.tickPixelInterval; if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial && !this.isLog && options.startOnTick && options.endOnTick) { tickAmount = 2; } if (!tickAmount && this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) { // Check if there are multiple axes in the same pane each(this.chart[this.coll], function (axis) { var options = axis.options, horiz = axis.horiz, key = [horiz ? options.left : options.top, horiz ? options.width : options.height, options.pane].join(','); if (axis.series.length) { // #4442 if (others[key]) { hasOther = true; // #4201 } else { others[key] = 1; } } }); if (hasOther) { // Add 1 because 4 tick intervals require 5 ticks (including first and last) tickAmount = mathCeil(this.len / tickPixelInterval) + 1; } } // For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This // prevents the axis from adding ticks that are too far away from the data extremes. if (tickAmount < 4) { this.finalTickAmt = tickAmount; tickAmount = 5; } this.tickAmount = tickAmount; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var tickInterval = this.tickInterval, tickPositions = this.tickPositions, tickAmount = this.tickAmount, finalTickAmt = this.finalTickAmt, currentTickAmount = tickPositions && tickPositions.length, i, len; if (currentTickAmount < tickAmount) { // TODO: Check #3411 while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + tickInterval )); } this.transA *= (currentTickAmount - 1) / (tickAmount - 1); this.max = tickPositions[tickPositions.length - 1]; // We have too many ticks, run second pass to try to reduce ticks } else if (currentTickAmount > tickAmount) { this.tickInterval *= 2; this.setTickPositions(); } // The finalTickAmt property is set in getTickAmount if (defined(finalTickAmt)) { i = len = tickPositions.length; while (i--) { if ( (finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick (finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last ) { tickPositions.splice(i, 1); } } this.finalTickAmt = UNDEFINED; } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { if (axis.resetStacks) { axis.resetStacks(); } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickInterval(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (axis.cleanStacks) { axis.cleanStacks(); } }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true each(axis.series, function (serie) { delete serie.kdTree; }); // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options, min = mathMin(dataMin, pick(options.min, dataMin)), max = mathMax(dataMax, pick(options.max, dataMax)); // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= min) { newMin = min; } if (defined(dataMax) && newMax >= max) { newMax = max; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // Check for percentage based input values if (percentRegex.test(height)) { height = parseFloat(height) / 100 * chart.plotHeight; } if (percentRegex.test(top)) { top = parseFloat(top) / 100 * chart.plotHeight + chart.plotTop; } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog, realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; // With a threshold of null, make the columns/areas rise from the top or bottom // depending on the value, assuming an actual threshold of 0 (#4233). if (threshold === null) { threshold = realMax < 0 ? realMax : realMin; } else if (realMin > threshold) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Prevent the ticks from getting so close we can't draw the labels. On a horizontal * axis, this is handled by rotating the labels, removing ticks and adding ellipsis. * On a vertical axis remove ticks and add ellipsis. */ unsquish: function () { var chart = this.chart, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, tickInterval = this.tickInterval, newTickInterval = tickInterval, slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval), rotation, rotationOption = labelOptions.rotation, labelMetrics = chart.renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label), step, bestScore = Number.MAX_VALUE, autoRotation, // Return the multiple of tickInterval that is needed to avoid collision getStep = function (spaceNeeded) { var step = spaceNeeded / (slotSize || 1); step = step > 1 ? mathCeil(step) : 1; return step * tickInterval; }; if (horiz) { autoRotation = !labelOptions.staggerLines && !labelOptions.step && ( // #3971 defined(rotationOption) ? [rotationOption] : slotSize < pick(labelOptions.autoRotationLimit, 80) && labelOptions.autoRotation ); if (autoRotation) { // Loop over the given autoRotation options, and determine which gives the best score. The // best score is that with the lowest number of steps and a rotation closest to horizontal. each(autoRotation, function (rot) { var score; if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891 step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot))); score = step + mathAbs(rot / 360); if (score < bestScore) { bestScore = score; rotation = rot; newTickInterval = step; } } }); } } else if (!labelOptions.step) { // #4411 newTickInterval = getStep(labelMetrics.h); } this.autoRotation = autoRotation; this.labelRotation = pick(rotation, rotationOption); return newTickInterval; }, renderUnsquish: function () { var chart = this.chart, renderer = chart.renderer, tickPositions = this.tickPositions, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, margin = chart.margin, slotCount = this.categories ? tickPositions.length : tickPositions.length - 1, slotWidth = this.slotWidth = (horiz && !labelOptions.step && !labelOptions.rotation && ((this.staggerLines || 1) * chart.plotWidth) / slotCount) || (!horiz && ((margin[3] && (margin[3] - chart.spacing[3])) || chart.chartWidth * 0.33)), // #1580, #1931, innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))), attr = {}, labelMetrics = renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label), textOverflowOption = labelOptions.style.textOverflow, css, labelLength = 0, label, i, pos; // Set rotation option unless it is "auto", like in gauges if (!isString(labelOptions.rotation)) { attr.rotation = labelOptions.rotation || 0; // #4443 } // Handle auto rotation on horizontal axis if (this.autoRotation) { // Get the longest label length each(tickPositions, function (tick) { tick = ticks[tick]; if (tick && tick.labelLength > labelLength) { labelLength = tick.labelLength; } }); // Apply rotation only if the label is too wide for the slot, and // the label is wider than its height. if (labelLength > innerWidth && labelLength > labelMetrics.h) { attr.rotation = this.labelRotation; } else { this.labelRotation = 0; } // Handle word-wrap or ellipsis on vertical axis } else if (slotWidth) { // For word-wrap or ellipsis css = { width: innerWidth + PX }; if (!textOverflowOption) { css.textOverflow = 'clip'; // On vertical axis, only allow word wrap if there is room for more lines. i = tickPositions.length; while (!horiz && i--) { pos = tickPositions[i]; label = ticks[pos].label; if (label) { // Reset ellipsis in order to get the correct bounding box (#4070) if (label.styles.textOverflow === 'ellipsis') { label.css({ textOverflow: 'clip' }); } if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) { label.specCss = { textOverflow: 'ellipsis' }; } } } } } // Add ellipsis if the label length is significantly longer than ideal if (attr.rotation) { css = { width: (labelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX }; if (!textOverflowOption) { css.textOverflow = 'ellipsis'; } } // Set the explicit or automatic label alignment this.labelAlign = attr.align = labelOptions.align || this.autoLabelAlign(this.labelRotation); // Apply general and specific CSS each(tickPositions, function (pos) { var tick = ticks[pos], label = tick && tick.label; if (label) { label.attr(attr); // This needs to go before the CSS in old IE (#4502) if (css) { label.css(merge(css, label.specCss)); } delete label.specCss; tick.rotation = attr.rotation; } }); // TODO: Why not part of getLabelPosition? this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side === 2); }, /** * Return true if the axis has associated data */ hasData: function () { return this.hasVisibleSeries || (defined(this.min) && defined(this.max) && !!this.tickPositions); }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset labelOffsetPadded, axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, clip, directionFactor = [-1, 1, 1, -1][side], n, axisParent = axis.axisParent, // Used in color axis lineHeightCorrection; // For reuse in Axis.render hasData = axis.hasData(); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(axisParent); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(axisParent); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .addClass(PREFIX + axis.coll.toLowerCase() + '-labels') .add(axisParent); } if (hasData || axis.isLinked) { // Generate ticks each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); axis.renderUnsquish(); each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .addClass(PREFIX + this.coll.toLowerCase() + '-title') .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleOffsetOption = axisTitleOptions.offset; titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10); } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar lineHeightCorrection = side === 2 ? axis.tickRotCorr.y : 0; labelOffsetPadded = labelOffset + titleMargin + (labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + 8) : labelOptions.x) - lineHeightCorrection)); axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset, labelOffsetPadded // #3027 ); // Decide the clipping needed to keep the graph inside the plot area and axis lines clip = options.offset ? 0 : mathFloor(options.lineWidth / 2) * 2; // #4308, #4371 clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], clip); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, xOption = axisTitleOptions.x || 0, yOption = axisTitleOptions.y || 0, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis + xOption : offAxis + (opposite ? this.width : 0) + offset + xOption, y: horiz ? offAxis + yOption - (opposite ? this.height : 0) + offset : alongAxis + yOption }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), showAxis = axis.showAxis, globalAnimation = renderer.globalAnimation, from, to; // Reset axis.labelEdge.length = 0; //axis.justifyToPlot = overflow === 'justify'; axis.overlap = false; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (axis.hasData() || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions, function (pos, i) { // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true, 0.1); } ticks[pos].render(i); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && (axis.min === 0 || axis.single)) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max - tickmarkOffset; if (i % 2 === 0 && pos < axis.max && to <= axis.max - tickmarkOffset) { // #2248 if (!alternateBands[pos]) { alternateBands[pos] = new Highcharts.PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them if (coll === alternateBands || !chart.hasRendered || !delay) { destroyInactiveItems(); } else if (delay) { setTimeout(destroyInactiveItems, delay); } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { if (this.visible) { // render the axis this.render(); // move plot lines and bands each(this.plotLinesAndBands, function (plotLine) { plotLine.render(); }); } // mark associated series as dirty and ready for redraw each(this.series, function (series) { series.isDirty = true; }); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); // Destroy crosshair if (this.cross) { this.cross.destroy(); } }, /** * Draw the crosshair */ drawCrosshair: function (e, point) { // docs: Missing docs for Axis.crosshair. Also for properties. var path, options = this.crosshair, animation = options.animation, pos, attribs, categorized; if ( // Disabled in options !this.crosshair || // Snap ((defined(point) || !pick(this.crosshair.snap, true)) === false) || // Not on this axis (#4095, #2888) (point && point.series && point.series[this.coll] !== this) ) { this.hideCrosshair(); } else { // Get the path if (!pick(options.snap, true)) { pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { /*jslint eqeq: true*/ pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834 /*jslint eqeq: false*/ } if (this.isRadial) { path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189 } else { path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189 } if (path === null) { this.hideCrosshair(); return; } // Draw the cross if (this.cross) { this.cross .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation); } else { categorized = this.categories && !this.isRadial; attribs = { 'stroke-width': options.width || (categorized ? this.transA : 1), stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'), zIndex: options.zIndex || 2 }; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } this.cross = this.chart.renderer.path(path).attr(attribs).add(); } } }, /** * Hide the crosshair. */ hideCrosshair: function () { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(Axis.prototype, AxisPlotLineOrBandExtension); /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min - getTZOffset(min)), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 minDate[setMilliseconds](interval >= timeUnits.second ? 0 : // #3935 count * mathFloor(minDate.getMilliseconds() / count)); // #3652, #3654 if (interval >= timeUnits.second) { // second minDate[setSeconds](interval >= timeUnits.minute ? 0 : // #3935 count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits.minute) { // minute minDate[setMinutes](interval >= timeUnits.hour ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits.hour) { // hour minDate[setHours](interval >= timeUnits.day ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits.day) { // day minDate[setDate](interval >= timeUnits.month ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits.month) { // month minDate[setMonth](interval >= timeUnits.year ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits.year) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits.week) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; if (timezoneOffset || getTimezoneOffset) { minDate = minDate.getTime(); minDate = new Date(minDate + getTZOffset(minDate)); } minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), localTimezoneOffset = (timeUnits.day + (useUTC ? getTZOffset(minDate) : minDate.getTimezoneOffset() * 60 * 1000) ) % timeUnits.day; // #950, #3359 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits.year) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits.month) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval === timeUnits.day || interval === timeUnits.week)) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits.day ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * count; } i++; } // push the last time tickPositions.push(time); // mark new days if the time is dividible by day (#1649, #1760) each(grep(tickPositions, function (time) { return interval <= timeUnits.hour && time % timeUnits.day === localTimezoneOffset; }), function (time) { higherRanks[time] = 'day'; }); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; }; /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) { var units = unitsOption || [[ 'millisecond', // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ 'second', [1, 2, 5, 10, 15, 30] ], [ 'minute', [1, 2, 5, 10, 15, 30] ], [ 'hour', [1, 2, 3, 4, 6, 8, 12] ], [ 'day', [1, 2] ], [ 'week', [1, 2] ], [ 'month', [1, 2, 3, 4, 6] ], [ 'year', null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits.year && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval( tickInterval / interval, multiples, unit[0] === 'year' ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360 ); return { unitRange: interval, count: count, unitName: unit[0] }; };/** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.getLogTickPositions = function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; };/** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ var Tooltip = Highcharts.Tooltip = function () { this.init.apply(this, arguments); }; Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add() .attr({ y: -9999 }); // #2301, #2657 // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden && // When we get close to the target position, abort animation and land on the right place (#3056) (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // Move to the intermediate value tooltip.label.attr(now); // Run on next tick of the mouse tracker if (animate) { // Never allow two timeouts clearTimeout(this.tooltipTimeout); // Set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function (delay) { var tooltip = this, hoverPoints; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) if (!this.isHidden) { hoverPoints = this.chart.hoverPoints; this.hideTimer = setTimeout(function () { tooltip.label.fadeOut(); tooltip.isHidden = true; }, pick(delay, this.options.hideDelay, 500)); } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotLeft = chart.plotLeft, plotX = 0, plotY = 0, yAxis, xAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; xAxis = point.series.xAxis; plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0); plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, h = point.h || 0, // #4117 swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop, chart.plotTop, chart.plotTop + chart.plotHeight], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft, chart.plotLeft, chart.plotLeft + chart.plotWidth], // The far side is right or bottom preferFarSide = pick(point.ttBelow, (chart.inverted && !point.negative) || (!chart.inverted && point.negative)), /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function (dim, outerSize, innerSize, point, min, max) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = mathMin(max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h); } else if (roomRight) { ret[dim] = mathMax(min, alignedRight + h + innerSize > outerSize ? alignedRight : alignedRight + h); } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function (dim, outerSize, innerSize, point) { // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { return false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } }, /** * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), s; // build the header s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header // build the values s = s.concat(tooltip.bodyFormatter(items)); // footer s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow, h: anchor[2] || 0 }); this.isHidden = false; } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y || 0), // can be undefined (#3977) point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); }, /** * Get the best X date format based on the closest point range on the axis. */ getXDateFormat: function (point, options, xAxis) { var xDateFormat, dateTimeLabelFormats = options.dateTimeLabelFormats, closestPointRange = xAxis && xAxis.closestPointRange, n, blank = '01-01 00:00:00.000', strpos = { millisecond: 15, second: 12, minute: 9, hour: 6, day: 3 }, date, lastN = 'millisecond'; // for sub-millisecond data, #4223 if (closestPointRange) { date = dateFormat('%m-%d %H:%M:%S.%L', point.x); for (n in timeUnits) { // If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek && date.substr(6) === blank.substr(6)) { n = 'week'; break; // The first format that is too great for the range } else if (timeUnits[n] > closestPointRange) { n = lastN; break; // If the point is placed every day at 23:59, we need to show // the minutes as well. #2637. } else if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) { break; } // Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition if (n !== 'week') { lastN = n; } } if (n) { xDateFormat = dateTimeLabelFormats[n]; } } else { xDateFormat = dateTimeLabelFormats.day; } return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 }, /** * Format the footer/header of the tooltip * #3397: abstraction to enable formatting of footer and header */ tooltipFooterHeaderFormatter: function (point, isFooter) { var footOrHead = isFooter ? 'footer' : 'header', series = point.series, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key), formatString = tooltipOptions[footOrHead+'Format']; // Guess the best date format based on the closest point distance (#568, #3418) if (isDateTime && !xDateFormat) { xDateFormat = this.getXDateFormat(point, tooltipOptions, xAxis); } // Insert the footer date format if any if (isDateTime && xDateFormat) { formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(formatString, { point: point, series: series }); }, /** * Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item, * abstracting this functionality allows to easily overwrite and extend it. */ bodyFormatter: function (items) { return map(items, function (item) { var tooltipOptions = item.series.tooltipOptions; return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat); }); } }; var hoverChartIndex; // Global flag for touch support hasTouch = doc.documentElement.ontouchstart !== UNDEFINED; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ var Pointer = Highcharts.Pointer = function (chart, options) { this.init(chart, options); }; Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.hasZoom = zoomX || zoomY; // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (Highcharts.Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = pick(options.tooltip.followTouchMove, true); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // common IE normalizing e = e || window.event; // Framework specific normalizing (#1165) e = washMouseEvent(e); // More IE normalizing, needs to go after washMouseEvent if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, shared = tooltip ? tooltip.shared : false, followPointer, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, distance = Number.MAX_VALUE, // #4511 anchor, noSharedTooltip, stickToHoverSeries, directTouch, kdpoints = [], kdpoint, kdpointT; // For hovering over the empty parts of the plot area (hoverSeries is undefined). // If there is one series with point tracking (combo chart), don't go to nearest neighbour. if (!shared && !hoverSeries) { for (i = 0; i < series.length; i++) { if (series[i].directTouch || !series[i].options.stickyTracking) { series = []; } } } // If it has a hoverPoint and that series requires direct touch (like columns, #3899), or we're on // a noSharedTooltip series among shared tooltip series (#4546), use the hoverPoint . Otherwise, // search the k-d tree. stickToHoverSeries = hoverSeries && (shared ? hoverSeries.noSharedTooltip : hoverSeries.directTouch); if (stickToHoverSeries && hoverPoint) { kdpoint = hoverPoint; // Handle shared tooltip or cases where a series is not yet hovered } else { // Find nearest points on all series each(series, function (s) { // Skip hidden series noSharedTooltip = s.noSharedTooltip && shared; directTouch = !shared && s.directTouch; if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821 kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828 if (kdpointT) { kdpoints.push(kdpointT); } } }); // Find absolute nearest point each(kdpoints, function (p) { if (p && typeof p.dist === 'number' && p.dist < distance) { distance = p.dist; kdpoint = p; } }); } // Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200 if (kdpoint && (kdpoint !== this.prevKDPoint || (tooltip && tooltip.isHidden))) { // Draw tooltip if necessary if (shared && !kdpoint.series.noSharedTooltip) { i = kdpoints.length; while (i--) { if (kdpoints[i].clientX !== kdpoint.clientX || kdpoints[i].series.noSharedTooltip) { kdpoints.splice(i, 1); } } if (kdpoints.length && tooltip) { tooltip.refresh(kdpoints, e); } // Do mouseover on all points (#3919, #3985, #4410) each(kdpoints, function (point) { point.onMouseOver(e, point !== ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoint)); }); } else { if (tooltip) { tooltip.refresh(kdpoint, e); } if(!hoverSeries || !hoverSeries.directTouch) { // #4448 kdpoint.onMouseOver(e); } } this.prevKDPoint = kdpoint; // Update positions (regardless of kdpoint or hoverPoint) } else { followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (tooltip && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } } // Start the event listener to pick up the tooltip if (tooltip && !pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.onDocumentMouseMove(e); } }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Crosshair each(chart.axes, function (axis) { axis.drawCrosshair(e, pick(kdpoint, hoverPoint)); }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove, delay) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, hoverPoints = chart.hoverPoints, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); each(chart.axes, function (axis) { if (pick(axis.options.crosshair && axis.options.crosshair.snap, true)) { axis.drawCrosshair(null, hoverPoint); } else { axis.hideCrosshair(); } }); } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(delay); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); pointer.hoverX = chart.hoverPoints = chart.hoverPoint = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, selectionMarker = this.selectionMarker, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY, panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key']; // If the device supports both touch and mouse (like IE11), and we are touch-dragging // inside the plot area, don't handle the mouse event. #4339. if (selectionMarker && selectionMarker.touch) { return; } // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) { if (!selectionMarker) { this.selectionMarker = selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (selectionMarker && zoomHor) { size = chartX - mouseDownX; selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (selectionMarker && zoomVert) { size = chartY - mouseDownY; selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var pointer = this, chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569 var horiz = axis.horiz, minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075 selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding); selectionData[axis.coll].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes max: mathMax(selectionMin, selectionMax) }); runZoom = true; } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { var chart = charts[hoverChartIndex]; if (chart) { chart.pointer.reset(); chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix } }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; hoverChartIndex = chart.index; e = this.normalize(e); e.returnValue = false; // #2251, #3224 if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement; if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') && !this.inClass(relatedTarget, PREFIX + 'series-' + series.index)) { // #2499, #4465 series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; e = this.normalize(e); e.originalEvent = e; // #3913 if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container; container.onmousedown = function (e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function (e) { pointer.onContainerMouseMove(e); }; container.onclick = function (e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (hasTouch) { container.ontouchstart = function (e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function (e) { pointer.onContainerTouchMove(e); }; if (chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; /* Support for touch devices */ extend(Highcharts.Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || self.runChartClick), clip = {}; // Don't initiate panning until the user has pinched. This prevents us from // blocking page scrolling as users scroll down a long page (#4210). if (touchesLength > 1) { self.initiated = true; } // On touch devices, only proceed to trigger click if a handler is defined if (hasZoom && self.initiated && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(pick(axis.options.min, axis.dataMin)), max = axis.toPixels(pick(axis.options.max, axis.dataMax)), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); self.res = true; // reset on next move // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop, touch: true }, chart.plotBox); } self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && self.followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } else if (self.res) { self.res = false; this.reset(false, 0); } } }, /** * General touch handler shared by touchstart and touchmove. */ touch: function (e, start) { var chart = this.chart; hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) { // Run mouse events and display tooltip etc if (start) { this.runPointActions(e); } this.pinch(e); } else if (start) { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchStart: function (e) { this.touch(e, true); }, onContainerTouchMove: function (e) { this.touch(e); }, onDocumentTouchEnd: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } } }); if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function () { var key, fake = []; fake.item = function (i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function (e, method, wktype, callback) { var p; e = e.originalEvent || e; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) { callback(e); p = charts[hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function (e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function (e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function (e) { translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function (e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function (fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom) { // #4014 css(chart.container, { '-ms-touch-action': NONE, 'touch-action': NONE }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function (proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function (proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } /** * The overview of the chart's series */ var Legend = Highcharts.Legend = function (chart, options) { this.init(chart, options); }; Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding, itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding = pick(options.padding, 8); legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.symbolWidth = pick(options.symbolWidth, 16); legend.pages = []; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 symbolAttr.stroke = symbolColor; markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox, legendGroup = item.legendGroup; if (legendGroup && legendGroup.element) { legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Set the legend item text */ setText: function (item) { var options = this.options; item.legendItem.attr({ text: options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item) }); }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( '', ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline || 0, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for all if (!legend.baseline) { legend.fontMetrics = renderer.fontMetrics(itemStyle.fontSize, li); legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle); } // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // Always update the text legend.setText(item); // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line (#915, #3976) } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function () { var allItems = []; each(this.chart.series, function (series) { var seriesOptions = series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); }); return allItems; }, /** * Adjust the chart margins by reserving space for the legend on only one side * of the chart. If the position is set to a corner, top or bottom is reserved * for horizontal legends and left or right for vertical ones. */ adjustMargins: function (margin, spacing) { var chart = this.chart, options = this.options, // Use the first letter of each alignment option in order to detect the side alignment = options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0); // #4189 - use charAt(x) notation instead of [x] for IE7 if (this.display && !options.floating) { each([ /(lth|ct|rth)/, /(rtv|rm|rbv)/, /(rbh|cb|lbh)/, /(lbv|lm|ltv)/ ], function (alignments, side) { if (alignments.test(alignment) && !defined(margin[side])) { // Now we have detected on which side of the chart we should reserve space for the legend chart[marginNames[side]] = mathMax( chart[marginNames[side]], chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] + [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] + pick(options.margin, 12) + spacing[side] ); } }); } }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items legend.lastLineHeight = 0; each(allItems, function (item) { legend.renderItem(item); }); // Get the box legendWidth = (options.width || legend.offsetWidth) + padding; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); legendHeight += padding; // Draw the border and/or background if (legendBorderWidth || legendBackgroundColor) { if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp({ width: legendWidth, height: legendHeight }) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, padding = this.padding, lastY, allItems = this.allItems, clipToHeight = function (height) { clipRect.attr({ height: height }); // useHTML if (legend.contentGroup.div) { legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)'; } }; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight) { this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function (item, i) { var y = item._legendItemPos[1], h = mathRound(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipToHeight(clipHeight); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipToHeight(chart.chartHeight); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ var LegendSymbolMixin = Highcharts.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function (legend, item) { var symbolHeight = legend.options.symbolHeight || legend.fontMetrics.f; item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - symbolHeight + 1, // #3988 legend.symbolWidth, symbolHeight, legend.options.symbolRadius || 0 ).attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(legend.fontMetrics.b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled !== false) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // TODO: Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue setTimeout(runPositionItem); }); } /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ var Chart = Highcharts.Chart = function () { this.init.apply(this, arguments); }; Chart.prototype = { /** * Hook for modules */ callbacks: [], /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data this.userOptions = userOptions; var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); chartCount++; // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = chart.colorCounter = chart.symbolCounter = 0; chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, hasCartesianSeries = chart.hasCartesianSeries, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // Handle updated data in the series each(series, function (serie) { if (serie.isDirty) { if (serie.options.legendType === 'point') { if (serie.updateTotals) { serie.updateTotals(); } redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } } chart.getMargins(); // #3098 if (hasCartesianSeries) { // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set var key = axis.min + ',' + axis.max; if (axis.extKey !== key) { // #821, #4452 axis.extKey = key; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray, axis; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions, redraw) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function (redraw) { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, requiresDirtyBox, renderer = this.renderer, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(subtitleOptions.style.fontSize, title).b }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) if (!defined(widthOption)) { chart.containerWidth = adapterRun(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = adapterRun(renderTo, 'height'); } chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(heightOption, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, options = chart.options, optionsChart = options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, Ren, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; // Initialize the renderer Ren = Highcharts[optionsChart.renderer] || Renderer; chart.renderer = new Ren( container, chartWidth, chartHeight, optionsChart.style, optionsChart.forExport, options.exporting && options.exporting.allowHTML ); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } // Add a reference to the charts index chart.renderer.chartIndex = chart.index; }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function (skipAxes) { var chart = this, spacing = chart.spacing, margin = chart.margin, titleOffset = chart.titleOffset; chart.resetMargins(); // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend chart.legend.adjustMargins(margin, spacing); // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } if (!skipAxes) { this.getAxisMargins(); } }, getAxisMargins: function () { var chart = this, axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left margin = chart.margin; // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { if (axis.visible) { axis.getOffset(); } }); } // Add the axis offsets each(marginNames, function (m, side) { if (!defined(margin[side])) { chart[m] += axisOffset[side]; } }); chart.setChartSize(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function (e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win, // #805 - MooTools doesn't supply e doReflow = function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }; // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093 if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(chart.reflowTimeout); if (e) { // Called from window.resize chart.reflowTimeout = setTimeout(doReflow, 100); } else { // Called directly (#2224) doReflow(); } } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function () { var chart = this, reflow = function (e) { chart.reflow(e); }; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize, renderer = chart.renderer, globalAnimation; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } // Resize the container with the global animation applied if enabled (#2503) globalAnimation = renderer.globalAnimation; (globalAnimation ? animate : css)(chart.container, { width: chartWidth + PX, height: chartHeight + PX }, globalAnimation); chart.setChartSize(true); renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.layOutTitles(); // #2857 chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // Fire endResize and set isResizing back. If animation is disabled, fire without delay globalAnimation = renderer.globalAnimation; // Reassign it before using it, it may have changed since the top of this function. if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2); clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this; each(marginNames, function (m, side) { chart[m] = pick(chart.margin[side], chart.spacing[side]); }); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .addClass(PREFIX + 'background') .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn }) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, fill: NONE, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879 } } }); }, /** * Render series for the chart */ renderSeries: function () { each(this.series, function (serie) { serie.translate(); serie.render(); }); }, /** * Render labels for the chart */ renderLabels: function () { var chart = this, labels = chart.options.labels; if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; chart.renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options, tempWidth, tempHeight, redoHorizontal, redoVertical; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); // Get stacks if (chart.getStacks) { chart.getStacks(); } // Get chart margins chart.getMargins(true); chart.setChartSize(); // Record preliminary dimensions for later comparison tempWidth = chart.plotWidth; tempHeight = chart.plotHeight = chart.plotHeight - 13; // 13 is the most common height of X axis labels // Get margins by pre-rendering axes each(axes, function (axis) { axis.setScale(); }); chart.getAxisMargins(); // If the plot area size has changed significantly, calculate tick positions again redoHorizontal = tempWidth / chart.plotWidth > 1.1; redoVertical = tempHeight / chart.plotHeight > 1.1; if (redoHorizontal || redoVertical) { chart.maxTicks = null; // reset for second pass each(axes, function (axis) { if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) { axis.setTickInterval(true); // update to reflect the new margins } }); chart.getMargins(); // second pass to check for new labels } // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { if (axis.visible) { axis.render(); } }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } chart.renderSeries(); // Labels chart.renderLabels(); // Credits chart.showCredits(options.credits); // Set flag chart.hasRendered = true; }, /** * Show chart credits based on config options */ showCredits: function (credits) { if (credits.enabled && !this.credits) { this.credits = this.renderer.text( credits.text, 0, 0 ) .on('click', function () { if (credits.href) { location.href = credits.href; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chartCount--; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set if (Highcharts.Pointer) { chart.pointer = new Pointer(chart, options); } chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { if (chart.index !== UNDEFINED) { // Chart destroyed in its own callback (#3600) fn.apply(chart, [chart]); } }); // Fire the load event fireEvent(chart, 'load'); // If the chart was rendered outside the top container, put it back in (#3679) chart.cloneRenderTo(true); }, /** * Creates arrays for spacing and margin from given options. */ splashArray: function (target, options) { var oVar = options[target], tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar]; return [pick(options[target + 'Top'], tArray[0]), pick(options[target + 'Right'], tArray[1]), pick(options[target + 'Bottom'], tArray[2]), pick(options[target + 'Left'], tArray[3])]; } }; // end Chart var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = { /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, slicingRoom = 2 * (options.slicedOffset || 0), handleSlicingRoom, plotWidth = chart.plotWidth - 2 * slicingRoom, plotHeight = chart.plotHeight - 2 * slicingRoom, centerOption = options.center, positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0], smallestSize = mathMin(plotWidth, plotHeight), i, value; for (i = 0; i < 4; ++i) { value = positions[i]; handleSlicingRoom = i < 2 || (i === 2 && /%$/.test(value)); // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 3: innerSize, relative to size positions[i] = relativeLength(value, [plotWidth, plotHeight, smallestSize, positions[2]][i]) + (handleSlicingRoom ? slicingRoom : 0); } // innerSize cannot be larger than size (#3632) if (positions[3] > positions[2]) { positions[3] = positions[2]; } return positions; } }; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.color = series.color; // #3445 point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.options.pointValKey || series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret = {}, series = this.series, keys = series.options.keys, pointArrayMap = keys || series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (!keys && options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { if (!keys || options[i] !== undefined) { // Skip undefined positions for keys ret[pointArrayMap[j]] = options[i]; } i++; j++; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { return { x: this.category, y: this.y, color: this.color, key: this.name || this.category, series: this.series, point: this, percentage: this.percentage, total: this.total || this.stackTotal }; }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera if (point.select) { // Could be destroyed by prior event handlers (#2911) point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); } }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, visible: true };/** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = Highcharts.Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, directTouch: false, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // Set the data each(series.parallelArrays, function (key) { series[key + 'Data'] = []; }); series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function (point, i) { var series = point.series, args = arguments, fn = typeof i === 'number' ? // Insert the value in the given position function (key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function (key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var options = this.options, xIncrement = this.xIncrement, date, pointInterval, pointIntervalUnit = options.pointIntervalUnit; xIncrement = pick(xIncrement, options.pointStart, 0); this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1); // Added code for pointInterval strings if (pointIntervalUnit === 'month' || pointIntervalUnit === 'year') { date = new Date(xIncrement); date = (pointIntervalUnit === 'month') ? +date[setMonth](date[getMonth]() + pointInterval) : +date[setFullYear](date[getFullYear]() + pointInterval); pointInterval = date - xIncrement; } this.xIncrement = xIncrement + pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.plotOptions || {}, typeOptions = plotOptions[this.type], options, zones; this.userOptions = itemOptions; // General series options take precedence over type options because otherwise, default // type options like column.animation would be overwritten by the general option. // But issues have been raised here (#3881), and the solution may be to distinguish // between default option and userOptions like in the tooltip below. options = merge( typeOptions, plotOptions.series, itemOptions ); // The tooltip options are merged between global and series specific options this.tooltipOptions = merge( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } // Handle color zones this.zoneAxis = options.zoneAxis; zones = this.zones = (options.zones || []).slice(); if ((options.negativeColor || options.negativeFillColor) && !options.zones) { zones.push({ value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0, color: options.negativeColor, fillColor: options.negativeFillColor }); } if (zones.length) { // Push one extra zone for the rest if (defined(zones[zones.length - 1].value)) { zones.push({ color: this.color, fillColor: this.fillColor }); } } return options; }, getCyclic: function (prop, value, defaults) { var i, userOptions = this.userOptions, indexName = '_' + prop + 'Index', counterName = prop + 'Counter'; if (!value) { if (defined(userOptions[indexName])) { // after Series.update() i = userOptions[indexName]; } else { userOptions[indexName] = i = this.chart[counterName] % defaults.length; this.chart[counterName] += 1; } value = defaults[i]; } this[prop] = value; }, /** * Get the series' color */ getColor: function () { if (this.options.colorByPoint) { this.options.color = null; // #4359, selected slice got series.color even when colorByPoint was set. } else { this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors); } }, /** * Get the series' symbol */ getSymbol: function () { var seriesMarkerOption = this.options.marker; this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols); // don't substract radius in image symbols (#604) if (/^url/.test(this.symbol)) { seriesMarkerOption.radius = 0; } }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, hasCategories = xAxis && !!xAxis.categories, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) { each(data, function (point, i) { if (oldData[i].update) { // Linked, previously hidden series (#3709) oldData[i].update(point, false, null, false); } }); } else { // Reset properties series.xIncrement = null; series.pointRange = hasCategories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function (key) { series[key + 'Data'].length = 0; }); // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); series.updateParallelArrays(pt, i); if (hasCategories && defined(pt.name)) { // #4401 xAxis.names[pt.x] = pt.name; // #2046 } } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; //series.zData = zData; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; animation = false; } // Typically for pie series, points need to be processed and generated // prior to rendering the legend if (options.legendType === 'point') { // docs: legendType now supported on more series types (at least column and pie) this.processData(); this.generatePoints(); } if (redraw) { chart.redraw(animation); } }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, getExtremesFromAll = series.getExtremesFromAll || options.getExtremesFromAll, // #4599 isCartesian = series.isCartesian, xExtremes, min, max; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } if (xAxis) { xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053) min = xExtremes.min; max = xExtremes.max; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && !getExtremesFromAll && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i >= 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function (xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = mathMax(0, i - cropShoulder); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (xData[i] > max) { cropEnd = i + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } points[i].index = cursor; // For faster access in Point.update } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Calculate Y extremes for visible data */ getExtremes: function (yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, x, y, i, j; yData = yData || this.stackedYData || this.processedYData; yDataLength = yData.length; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = arrayMin(activeYData); this.dataMax = arrayMax(activeYData); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold, stackThreshold = options.startFromThreshold ? threshold : 0, plotX, plotY, lastPlotX, stackIndicator, closestPointRangePx = Number.MAX_VALUE; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes (#3434) if (yAxis.isLog && yValue !== null && yValue <= 0) { point.y = yValue = null; error(10); } // Get the plotX translation point.plotX = plotX = mathMin(mathMax(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5); // #3923 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { stackIndicator = series.getStackIndicator(stackIndicator, xValue, series.index); pointStack = stack[xValue]; stackValues = pointStack.points[stackIndicator.key]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === stackThreshold) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = pointStack.total && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ? mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201 UNDEFINED; point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519 plotX >= 0 && plotX <= xAxis.len; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; // Determine auto enabling of markers (#3635) if (i) { closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX)); } lastPlotX = plotX; } series.closestPointRangePx = closestPointRangePx; // now that we have the cropped data, build the segments series.getSegments(); }, /** * Set the clipping for the series. For animated series it is called twice, first to initiate * animating the clip then the second time without the animation to set the final clip. */ setClip: function (animation) { var chart = this.chart, options = this.options, renderer = chart.renderer, inverted = chart.inverted, seriesClipBox = this.clipBox, clipBox = seriesClipBox || chart.clipBox, sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height, options.xAxis, options.yAxis].join(','), // #4526 clipRect = chart[sharedClipKey], markerClipRect = chart[sharedClipKey + 'm']; // If a clipping rectangle with the same properties is currently present in the chart, use that. if (!clipRect) { // When animation is set, prepare the initial positions if (animation) { clipBox.width = 0; chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox); } if (animation) { clipRect.count += 1; } if (options.clip !== false) { this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect); this.markerGroup.clip(markerClipRect); this.sharedClipKey = sharedClipKey; } // Remove the shared clipping rectangle when all series are shown if (!animation) { clipRect.count -= 1; if (clipRect.count <= 0 && sharedClipKey && chart[sharedClipKey]) { if (!seriesClipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } } } }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, clipRect, animation = series.options.animation, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } // Initialize the animation. Set up the clipping rectangle. if (init) { series.setClip(animation); // Run the animation } else { sharedClipKey = this.sharedClipKey; clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { this.setClip(); fireEvent(this, 'afterAnimate'); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, seriesPointAttr = series.pointAttr[''], pointMarkerOptions, hasPointMarker, enabled, isInside, markerGroup = series.markerGroup, xAxis = series.xAxis, globallyEnabled = pick( seriesMarkerOptions.enabled, xAxis.isRadial, series.closestPointRangePx > 2 * seriesMarkerOptions.radius ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; hasPointMarker = !!point.marker; enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = point.isInside; // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius, hasPointMarker ? pointMarkerOptions : seriesMarkerOptions ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, seriesNegativeColor = series.options.negativeColor, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, j, threshold, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions = series.hasPointSpecificOptions, defaultLineColor = normalOptions.lineColor, defaultFillColor = normalOptions.fillColor, turboThreshold = seriesOptions.turboThreshold, zones = series.zones, zoneAxis = series.zoneAxis || 'y', attr, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); // if no hover negativeColor is given, brighten the normal negativeColor stateOptionsHover.negativeColor = stateOptionsHover.negativeColor || Color(stateOptionsHover.negativeColor || seriesNegativeColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) { while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (zones.length) { j = 0; threshold = zones[j]; while (point[zoneAxis] >= threshold.value) { threshold = zones[++j]; } point.color = point.fillColor = pick(threshold.color, series.color); // #3636, #4267, #4430 - inherit color from series, when color is undefined } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker || (point.negative && !pointStateOptionsHover.fillColor && !stateOptionsHover.fillColor)) { // column, bar, point or negative threshold for series with markers (#3636) // If no hover color is given, brighten the normal color. #1619, #2579 pointStateOptionsHover[series.pointAttrToOptions.fill] = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) || Color(point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness) .get(); } // normal point state inherits series wide normal state attr = { color: point.color }; // #868 if (!defaultFillColor) { // Individual point color or negative color markers (#2219) attr.fillColor = point.color; } if (!defaultLineColor) { attr.lineColor = point.color; // Bubbles take point color, line markers use white } // Color is explicitly set to null or undefined (#1288, #4068) if (normalOptions.hasOwnProperty('color') && !normalOptions.color) { delete normalOptions.color; } pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(series.axisTypes || [], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // Destroy all SVGElements associated to the series for (prop in series) { if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } } // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY, L ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, L, (lastPoint.plotX + plotX) / 2, plotY, L ); } else { segmentPath.push( plotX, lastPoint.plotY, L ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color, options.dashStyle]], lineWidth = options.lineWidth, roundCap = options.linecap !== 'square', graphPath = this.getGraphPath(), fillColor = (this.fillGraph && this.color) || NONE, // polygon series use filled graph zones = this.zones; each(zones, function (threshold, i) { props.push(['zoneGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]); }); // Draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { graph.animate({ d: graphPath }); } else if ((lineWidth || fillColor) && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, fill: fillColor, zIndex: 1 // #1069 }; if (prop[2]) { attribs.dashstyle = prop[2]; } else if (roundCap) { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow((i < 2) && options.shadow); // add shadow to normal series (0) or to first zone (1) #3932 } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ applyZones: function () { var series = this, chart = this.chart, renderer = chart.renderer, zones = this.zones, translatedFrom, translatedTo, clips = this.clips || [], clipAttr, graph = this.graph, area = this.area, chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight), axis = this[(this.zoneAxis || 'y') + 'Axis'], extremes, reversed = axis.reversed, inverted = chart.inverted, horiz = axis.horiz, pxRange, pxPosMin, pxPosMax, ignoreZones = false; if (zones.length && (graph || area) && axis.min !== UNDEFINED) { // The use of the Color Threshold assumes there are no gaps // so it is safe to hide the original graph and area if (graph) { graph.hide(); } if (area) { area.hide(); } // Create the clips extremes = axis.getExtremes(); each(zones, function (threshold, i) { translatedFrom = reversed ? (horiz ? chart.plotWidth : 0) : (horiz ? 0 : axis.toPixels(extremes.min)); translatedFrom = mathMin(mathMax(pick(translatedTo, translatedFrom), 0), chartSizeMax); translatedTo = mathMin(mathMax(mathRound(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax); if (ignoreZones) { translatedFrom = translatedTo = axis.toPixels(extremes.max); } pxRange = Math.abs(translatedFrom - translatedTo); pxPosMin = mathMin(translatedFrom, translatedTo); pxPosMax = mathMax(translatedFrom, translatedTo); if (axis.isXAxis) { clipAttr = { x: inverted ? pxPosMax : pxPosMin, y: 0, width: pxRange, height: chartSizeMax }; if (!horiz) { clipAttr.x = chart.plotHeight - clipAttr.x; } } else { clipAttr = { x: 0, y: inverted ? pxPosMax : pxPosMin, width: chartSizeMax, height: pxRange }; if (horiz) { clipAttr.y = chart.plotWidth - clipAttr.y; } } /// VML SUPPPORT if (chart.inverted && renderer.isVML) { if (axis.isXAxis) { clipAttr = { x: 0, y: reversed ? pxPosMin : pxPosMax, height: clipAttr.width, width: chart.chartWidth }; } else { clipAttr = { x: clipAttr.y - chart.plotLeft - chart.spacingBox.x, y: 0, width: clipAttr.height, height: chart.chartHeight }; } } /// END OF VML SUPPORT if (clips[i]) { clips[i].animate(clipAttr); } else { clips[i] = renderer.clipRect(clipAttr); if (graph) { series['zoneGraph' + i].clip(clips[i]); } if (area) { series['zoneArea' + i].clip(clips[i]); } } // if this zone extends out of the axis, ignore the others ignoreZones = threshold.value > extremes.max; }); this.clips = clips; } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); group.addClass('highcharts-series-' + this.index); } // Place it on first and subsequent (redraw) calls group[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function () { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0, visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (animDuration) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.applyZones(); } each(series.points, function (point) { if (point.redraw) { point.redraw(); } }); // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839). if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { if (animDuration) { series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animDuration); } else { series.afterAnimate(); } } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after wasDirty = series.isDirty, group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } if (wasDirty || wasDirtyData) { // #3945 recalculate the kdtree when dirty delete this.kdTree; // #3868 recalculate the kdtree with dirty data } }, /** * KD Tree && PointSearching Implementation */ kdDimensions: 1, kdAxisArray: ['clientX', 'plotY'], searchPoint: function (e, compareX) { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, inverted = series.chart.inverted; return this.searchKDTree({ clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos, plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos }, compareX); }, buildKDTree: function () { var series = this, dimensions = series.kdDimensions; // Internal function function _kdtree(points, depth, dimensions) { var axis, median, length = points && points.length; if (length) { // alternate between the axis axis = series.kdAxisArray[depth % dimensions]; // sort point array points.sort(function(a, b) { return a[axis] - b[axis]; }); median = Math.floor(length / 2); // build and return nod return { point: points[median], left: _kdtree(points.slice(0, median), depth + 1, dimensions), right: _kdtree(points.slice(median + 1), depth + 1, dimensions) }; } } // Start the recursive build process with a clone of the points array and null points filtered out (#3873) function startRecursive() { var points = grep(series.points || [], function (point) { // #4390 return point.y !== null; }); series.kdTree = _kdtree(points, dimensions, dimensions); } delete series.kdTree; if (series.options.kdSync) { // For testing tooltips, don't build async startRecursive(); } else { setTimeout(startRecursive); } }, searchKDTree: function (point, compareX) { var series = this, kdX = this.kdAxisArray[0], kdY = this.kdAxisArray[1], kdComparer = compareX ? 'distX' : 'dist'; // Set the one and two dimensional distance on the point object function setDistance(p1, p2) { var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null, y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null, r = (x || 0) + (y || 0); p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE; p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE; } function _search(search, tree, depth, dimensions) { var point = tree.point, axis = series.kdAxisArray[depth % dimensions], tdist, sideA, sideB, ret = point, nPoint1, nPoint2; setDistance(search, point); // Pick side based on distance to splitting point tdist = search[axis] - point[axis]; sideA = tdist < 0 ? 'left' : 'right'; sideB = tdist < 0 ? 'right' : 'left'; // End of tree if (tree[sideA]) { nPoint1 =_search(search, tree[sideA], depth + 1, dimensions); ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point); } if (tree[sideB]) { // compare distance to current best to splitting point to decide wether to check side B or not if (Math.sqrt(tdist * tdist) < ret[kdComparer]) { nPoint2 = _search(search, tree[sideB], depth + 1, dimensions); ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret); } } return ret; } if (!this.kdTree) { this.buildKDTree(); } if (this.kdTree) { return _search(point, this.kdTree, this.kdDimensions, this.kdDimensions); } } }; // end Series prototype /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Initialize total value this.total = null; // This will keep each points' extremes stored by series.index and point index this.points = {}; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, formatOption = options.format, str = formatOption ? format(formatOption, this) : options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({text: str, visibility: HIDDEN}); // Create new label } else { this.label = this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries .css(options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, reversed = axis.reversed, neg = (this.isNegative && !reversed) || (!this.isNegative && reversed), // #4056 y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true); } } }; /** * Generate stacks for each series and calculate stacks total values */ Chart.prototype.getStacks = function () { var chart = this; // reset stacks for each yAxis each(chart.yAxis, function (axis) { if (axis.stacks && axis.hasVisibleSeries) { axis.oldStacks = axis.stacks; } }); each(chart.series, function (series) { if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) { series.stackKey = series.type + pick(series.options.stack, ''); } }); }; // Stacking methods defined on the Axis prototype /** * Build the stacks from top down */ Axis.prototype.buildStacks = function () { var series = this.series, reversedStacks = pick(this.options.reversedStacks, true), i = series.length; if (!this.isXAxis) { this.usePercentage = false; while (i--) { series[reversedStacks ? i : series.length - i - 1].setStackedPoints(); } // Loop up again to compute percent stack if (this.usePercentage) { for (i = 0; i < series.length; i++) { series[i].setPercentStacks(); } } } }; Axis.prototype.renderStackTotals = function () { var axis = this, chart = axis.chart, renderer = chart.renderer, stacks = axis.stacks, stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } }; /** * Set all the stacks to initial states and destroy unused ones. */ Axis.prototype.resetStacks = function () { var stacks = this.stacks, type, i; if (!this.isXAxis) { for (type in stacks) { for (i in stacks[type]) { // Clean up memory after point deletion (#1044, #4320) if (stacks[type][i].touched < this.stacksTouched) { stacks[type][i].destroy(); delete stacks[type][i]; // Reset stacks } else { stacks[type][i].total = null; stacks[type][i].cum = 0; } } } } }; Axis.prototype.cleanStacks = function () { var stacks, type, i; if (!this.isXAxis) { if (this.oldStacks) { stacks = this.stacks = this.oldStacks; } // reset stacks for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } }; // Stacking methods defnied for Series prototype /** * Adds series' points value to corresponding stack */ Series.prototype.setStackedPoints = function () { if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) { return; } var series = this, xData = series.processedXData, yData = series.processedYData, stackedYData = [], yDataLength = yData.length, seriesOptions = series.options, threshold = seriesOptions.threshold, stackThreshold = seriesOptions.startFromThreshold ? threshold : 0, stackOption = seriesOptions.stack, stacking = seriesOptions.stacking, stackKey = series.stackKey, negKey = '-' + stackKey, negStacks = series.negStacks, yAxis = series.yAxis, stacks = yAxis.stacks, oldStacks = yAxis.oldStacks, stackIndicator, isNegative, stack, other, key, pointKey, i, x, y; yAxis.stacksTouched += 1; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; stackIndicator = series.getStackIndicator(stackIndicator, x, series.index); pointKey = stackIndicator.key; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) isNegative = negStacks && y < (stackThreshold ? 0 : threshold); key = isNegative ? negKey : stackKey; // Create empty object for this stack if it doesn't exist yet if (!stacks[key]) { stacks[key] = {}; } // Initialize StackItem for this x if (!stacks[key][x]) { if (oldStacks[key] && oldStacks[key][x]) { stacks[key][x] = oldStacks[key][x]; stacks[key][x].total = null; } else { stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption); } } // If the StackItem doesn't exist, create it first stack = stacks[key][x]; //stack.points[pointKey] = [stack.cum || stackThreshold]; stack.points[pointKey] = [pick(stack.cum, stackThreshold)]; stack.touched = yAxis.stacksTouched; // Add value to the stack total if (stacking === 'percent') { // Percent stacked column, totals are the same for the positive and negative stacks other = isNegative ? stackKey : negKey; if (negStacks && stacks[other] && stacks[other][x]) { other = stacks[other][x]; stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0; // Percent stacked areas } else { stack.total = correctFloat(stack.total + (mathAbs(y) || 0)); } } else { stack.total = correctFloat(stack.total + (y || 0)); } stack.cum = pick(stack.cum, stackThreshold) + (y || 0); stack.points[pointKey].push(stack.cum); stackedYData[i] = stack.cum; } if (stacking === 'percent') { yAxis.usePercentage = true; } this.stackedYData = stackedYData; // To be used in getExtremes // Reset old stacks yAxis.oldStacks = {}; }; /** * Iterate over all stacks and compute the absolute values to percent */ Series.prototype.setPercentStacks = function () { var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks, processedXData = series.processedXData, stackIndicator; each([stackKey, '-' + stackKey], function (key) { var i = processedXData.length, x, stack, pointExtremes, totalFactor; while (i--) { x = processedXData[i]; stackIndicator = series.getStackIndicator(stackIndicator, x, series.index); stack = stacks[key] && stacks[key][x]; pointExtremes = stack && stack.points[stackIndicator.key]; if (pointExtremes) { totalFactor = stack.total ? 100 / stack.total : 0; pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value series.stackedYData[i] = pointExtremes[1]; } } }); }; /** * Get stack indicator, according to it's x-value, to determine points with the same x-value */ Series.prototype.getStackIndicator = function(stackIndicator, x, index) { if (!defined(stackIndicator) || stackIndicator.x !== x) { stackIndicator = { x: x, index: 0 }; } else { stackIndicator.index++; } stackIndicator.key = [index, x, stackIndicator.index].join(','); return stackIndicator; }; // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, axis; /*jslint unused: false*/ axis = new Axis(this, merge(options, { index: this[key].length, isX: isX })); /*jslint unused: true*/ // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv, loadingOptions = options.loading, setLoadingSize = function () { if (loadingDiv) { css(loadingDiv, { left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); } }; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); addEvent(chart, 'redraw', setLoadingSize); // #1080 } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } setLoadingSize(); }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation, runEvent) { var point = this, series = point.series, graphic = point.graphic, i, chart = series.chart, seriesOptions = series.options, names = series.xAxis && series.xAxis.names; redraw = pick(redraw, true); function update() { point.applyOptions(options); // Update visuals if (point.y === null && graphic) { // #4146 point.graphic = graphic.destroy(); } if (isObject(options) && !isArray(options)) { // Defer the actual redraw until getAttribs has been called (#3260) point.redraw = function () { if (graphic && graphic.element) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } point.redraw = null; }; } // record changes in the parallel arrays i = point.index; series.updateParallelArrays(point, i); if (names && point.name) { names[point.x] = point.name; } seriesOptions.data[i] = point.options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 chart.isDirtyLegend = true; } if (redraw) { chart.redraw(animation); } } // Fire the event with a default handler of doing the update if (runEvent === false) { // When called from setData update(); } else { point.firePointEvent('update', { options: options }, update); } }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { this.series.removePoint(inArray(this, this.series.data), redraw, animation); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, names = series.xAxis && series.xAxis.names, currentShift = (graph && graph.shift) || 0, shiftShapes = ['graph', 'area'], dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, i, x; setAnimation(animation, chart); // Make graph animate sideways if (shift) { i = series.zones.length; while (i--) { shiftShapes.push('zoneGraph' + i, 'zoneArea' + i); } each(shiftShapes, function (shape) { if (series[shape]) { series[shape].shift = currentShift + (seriesOptions.step ? 2 : 1); } }); } if (area) { area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names && point.name) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * Remove a point (rendered or not), by index */ removePoint: function (i, redraw, animation) { var series = this, data = series.data, point = data[i], points = series.points, chart = series.chart, remove = function () { if (data.length === points.length) { points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.updateParallelArrays(point || { series: series }, 'splice', i, 1); if (point) { point.destroy(); } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }; setAnimation(animation, chart); redraw = pick(redraw, true); // Fire the event with a default handler of removing the point if (point) { point.firePointEvent('remove', null, remove); } else { remove(); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var series = this, chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, preserve = ['group', 'markerGroup', 'dataLabelsGroup'], n; // If we're changing type or zIndex, create new groups (#3380, #3404) if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) { preserve.length = 0; } // Make sure groups are not destroyed (#3094) each(preserve, function (prop) { preserve[prop] = series[prop]; delete series[prop]; }); // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and delete all properties. Reinsert all methods // and properties from the new type prototype (#2270, #3719) this.remove(false); for (n in proto) { this[n] = UNDEFINED; } extend(this, seriesTypes[newOptions.type || oldType].prototype); // Re-register groups (#3094) each(preserve, function (prop) { series[prop] = preserve[prop]; }); this.init(chart, newOptions); chart.linkSeries(); // Links are lost in this.remove (#3028) if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = this.chart._labelPanes = UNDEFINED; // #1611, #2887, #4314 this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].remove(false); } } // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); } }); /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { softThreshold: false, threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', /** * For stacks, don't split segments on null values. Instead, draw null values with * no marker. Also insert dummy points for any X position that exists in other series * in the stack. */ getSegments: function () { var series = this, segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, connectNulls = this.options.connectNulls, stackIndicator, i, x; if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue // Create a map where we can quickly look up the points by their X value. for (i = 0; i < points.length; i++) { pointMap[points[i].x] = points[i]; } // Sort the keys (#1651) for (x in stack) { if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336) keys.push(+x); } } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { var threshold = null, stackPoint; if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836 return; // The point exists, push it to the segment } else if (pointMap[x]) { segment.push(pointMap[x]); // There is no point for this X value in this series, so we // insert a dummy point in order for the areas to be drawn // correctly. } else { // Loop down the stack to find the series below this one that has // a value (#1991) for (i = series.index; i <= yAxis.series.length; i++) { stackIndicator = series.getStackIndicator(null, x, i); stackPoint = stack[x].points[stackIndicator.key]; if (stackPoint) { threshold = stackPoint[1]; break; } } plotX = xAxis.translate(x); plotY = yAxis.getThreshold(threshold); segment.push({ y: null, plotX: plotX, clientX: plotX, plotY: plotY, yBottom: plotY, onMouseOver: noop }); } }); if (segment.length) { segments.push(segment); } } else { Series.prototype.getSegments.call(this); segments = this.segments; } this.segments = segments; }, /** * Extend the base Series getSegmentPath method by adding the path for the area. * This path is pushed to the series.areaPath property. */ getSegmentPath: function (segment) { var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path i, options = this.options, segLength = segmentPath.length, translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181 yBottom; if (segLength === 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && !this.closedStacks) { // Follow stack back. Todo: implement areaspline. A general solution could be to // reverse the entire graphPath of the previous series, though may be hard with // splines and with series with different extremes for (i = segment.length - 1; i >= 0; i--) { yBottom = pick(segment[i].yBottom, translatedThreshold); // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, yBottom); } areaSegmentPath.push(segment[i].plotX, yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment, translatedThreshold); } this.areaPath = this.areaPath.concat(areaSegmentPath); return segmentPath; }, /** * Extendable method to close the segment path of an area. This is overridden in polar * charts. */ closeSegment: function (path, segment, translatedThreshold) { path.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var series = this, areaPath = this.areaPath, options = this.options, zones = this.zones, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color each(zones, function (threshold, i) { props.push(['zoneArea' + i, threshold.color || series.color, threshold.fillColor || options.fillColor]); }); each(props, function (prop) { var areaKey = prop[0], area = series[areaKey]; // Create or update the area if (area) { // update area.animate({ d: areaPath }); } else { // create series[areaKey] = series.chart.renderer.path(areaPath) .attr({ fill: pick( prop[2], Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get() ), zIndex: 0 // #1069 }).add(series.group); } }); }, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.area = AreaSeries; /** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (lastPoint && nextPoint) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 1 }) .add(); this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 1 }) .add(); } */ // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', closedStacks: true, // instead of following the previous graph back, follow the threshold back // Mix in methods from the area series getSegmentPath: areaProto.getSegmentPath, closeSegment: areaProto.closeSegment, drawGraph: areaProto.drawGraph, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', //borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false, halo: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, softThreshold: false, startFromThreshold: true, // docs (but false doesn't work well): http://jsfiddle.net/highcharts/hz8fopan/14/ stickyTracking: false, tooltip: { distance: 6 }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply. trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnIndex, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function (otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610 xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, pointWidth = mathMin( options.maxPointWidth || xAxis.len, pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding)) ), pointPadding = (pointOffsetWidth - pointWidth) / 2, colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) return (series.columnMetrics = { width: pointWidth, offset: pointXOffset }); }, /** * Make the columns crisp. The edges are rounded to the nearest full pixel. */ crispCol: function (x, y, w, h) { var chart = this.chart, borderWidth = this.borderWidth, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1, right, bottom, fromTop; if (chart.inverted && chart.renderer.isVML) { yCrisp += 1; } // Horizontal. We need to first compute the exact right edge, then round it // and compute the width from there. right = Math.round(x + w) + xCrisp; x = Math.round(x) + xCrisp; w = right - x; // Vertical fromTop = mathAbs(y) <= 0.5; // #4504 bottom = Math.round(y + h) + yCrisp; y = Math.round(y) + yCrisp; h = bottom - y; // Top edges are exceptions if (fromTop) { y -= 1; h += 1; } return { x: x, y: y, width: w, height: h }; }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = series.borderWidth = pick( options.borderWidth, series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset; if (chart.inverted) { translatedThreshold -= 0.5; // #3355 } // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual // columns to have individual sizes. When pointPadding is greater, we strive for equal-width // columns (#2694). if (options.pointPadding) { seriesBarW = mathCeil(seriesBarW); } Series.prototype.translate.apply(series); // Record the new values each(series.points, function (point) { var yBottom = mathMin(pick(point.yBottom, translatedThreshold), 9e4), // #3575 safeDistance = 999 + mathAbs(yBottom), plotY = mathMin(mathMax(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), up, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative); barY = mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (up ? minPointLength : 0); // #1485, #4051 } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Fix the tooltip on center of grouped columns (#1216, #424, #3648) point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH]; // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = series.crispCol(barX, barY, barW, barH); }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs, pointAttr; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic, borderAttr; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; borderAttr = defined(series.borderWidth) ? { 'stroke-width': series.borderWidth } : {}; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE]; if (graphic) { // update stop(graphic); graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(borderAttr) .attr(pointAttr) .add(point.group || series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, marker: { enabled: true // Overrides auto-enabling in line series (#3647) }, tooltip: { headerFormat: '<span style="color:{point.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' } }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], takeOrdinalPosition: false, // #2342 kdDimensions: 2, drawGraph: function () { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: [null, null], clip: false, colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { // #2945 return this.y === null ? undefined : this.point.name; }, // softConnector: true, x: 0 // y: 0 }, ignoreHiddenPoint: true, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: null, showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } }, stickyTracking: false, tooltip: { followPointer: true } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; point.name = pick(point.name, 'Slice'); // add event listener for select toggleSlice = function (e) { point.slice(e.type === 'select'); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis, redraw) { var point = this, series = point.series, chart = series.chart, ignoreHiddenPoint = series.options.ignoreHiddenPoint; redraw = pick(redraw, ignoreHiddenPoint); if (vis !== point.visible) { // If called without an argument, toggle visibility point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data // Show and hide associated elements. This is performed regardless of redraw or not, // because chart.redraw only handles full series. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][vis ? 'show' : 'hide'](true); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // #4170, hide halo after hiding point if (!vis && point.state === 'hover') { point.setState(''); } // Handle ignore hidden slices if (ignoreHiddenPoint) { series.isDirty = true; } if (redraw) { chart.redraw(); } } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data translation = sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; point.graphic.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } }, haloPath: function (size) { var shapeArgs = this.shapeArgs, chart = this.series.chart; return this.sliced || !this.visible ? [] : this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, { innerR: this.shapeArgs.r, start: shapeArgs.start, end: shapeArgs.end }); } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, directTouch: true, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], axisTypes: [], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * Animate the pies in */ animate: function (init) { var series = this, points = series.points, startAngleRad = series.startAngleRad; if (!init) { each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: point.startR || (series.center[3] / 2), // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Recompute total chart sum and update percentages of points. */ updateTotals: function () { var i, total = 0, points = this.points, len = points.length, point, ignoreHiddenPoint = this.options.ignoreHiddenPoint; // Get the total sum for (i = 0; i < len; i++) { point = points[i]; total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } this.total = total; // Set each point's properties for (i = 0; i < len; i++) { point = points[i]; point.percentage = (total > 0 && (point.visible || !ignoreHiddenPoint)) ? point.y / total * 100 : 0; point.total = total; } }, /** * Extend the generatePoints method by adding total and percentage properties to each point */ generatePoints: function () { Series.prototype.generatePoints.call(this); this.updateTotals(); }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngle = options.startAngle || 0, startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90), endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90), circ = endAngleRad - startAngleRad, //2 * mathPI, points = series.points, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // Get positions - either an integer or a percentage string must be given. // If positions are passed as a parameter, we're in a recursive loop for adjusting // space for data labels. if (!positions) { series.center = positions = series.getCenter(); } // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle start = startAngleRad + (cumulative * circ); if (!ignoreHiddenPoint || point.visible) { cumulative += point.percentage / 100; } end = startAngleRad + (cumulative * circ); // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: mathRound(start * precision) / precision, end: mathRound(end * precision) / precision }; // The angle must stay within -90 and 270 (#2645) angle = (end + start) / 2; if (angle > 1.5 * mathPI) { angle -= 2 * mathPI; } else if (angle < -mathPI / 2) { angle += 2 * mathPI; } // Center for the sliced out slice point.slicedTranslation = { translateX: mathRound(mathCos(angle) * slicedOffset), translateY: mathRound(mathSin(angle) * slicedOffset) }; // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0; point.angle = angle; // set the anchor point for data labels connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678 point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; } }, drawGraph: null, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, //group, shadow = series.options.shadow, shadowGroup, shapeArgs, attr; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { if (point.y !== null) { graphic = point.graphic; shapeArgs = point.shapeArgs; shadowGroup = point.shadowGroup; // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .add(series.shadowGroup); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; //group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.attr(groupTranslation); } // draw the slice if (graphic) { graphic .setRadialReference(series.center) .animate(extend(shapeArgs, groupTranslation)); } else { attr = { 'stroke-linejoin': 'round' }; if (!point.visible) { attr.visibility = 'hidden'; } point.graphic = graphic = renderer[point.shapeType](shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr(attr) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } } }); }, searchPoint: noop, /** * Utility for sorting data labels */ sortByAngle: function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }, /** * Use a simple symbol from LegendSymbolMixin */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Use the getCenter method from drawLegendSymbol */ getCenter: CenteredSeriesMixin.getCenter, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; /** * Draw the data labels */ Series.prototype.drawDataLabels = function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, hasRendered = series.hasRendered || 0, str, dataLabelsGroup, renderer = series.chart.renderer; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', options.defer ? HIDDEN : VISIBLE, options.zIndex || 6 ); if (pick(options.defer, true)) { dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300 if (!hasRendered) { addEvent(series, 'afterAnimate', function () { if (series.visible) { // #3023, #3024 dataLabelsGroup.show(); } dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } } // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true, style, moreStyle = {}; // Determine if each data label is enabled pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); style = options.style; rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color style.color = pick(options.color, style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Get automated contrast color if (style.color === 'contrast') { moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ? renderer.getContrast(point.color || series.color) : '#000000'; } if (cursor) { moreStyle.cursor = cursor; } // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, options.shape, null, null, options.useHTML ) .attr(attr) .css(extend(style, moreStyle)) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }; /** * Align each individual data label */ Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), baseline = chart.renderer.fontMetrics(options.style.fontSize).b, rotCorr, // rotation correction // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))), alignAttr; // the final position; if (visible) { // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text rotCorr = chart.renderer.rotCorr(baseline, options.rotation); // #3723 dataLabel[isNew ? 'attr' : 'animate']({ x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x, y: alignTo.y + options.y + alignTo.height / 2 }) .attr({ // #3003 align: options.align }); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; // Handle justify or crop if (pick(options.overflow, 'justify') === 'justify') { this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); } else if (pick(options.crop, true)) { // Now check that the data label is within the plot area visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } // When we're using a shape, make it possible with a connector or an arrow pointing to thie point if (options.shape) { dataLabel.attr({ anchorX: point.plotX, anchorY: point.plotY }); } } } // Show or hide based on the final aligned position if (!visible) { stop(dataLabel); dataLabel.attr({ y: -999 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified, padding = dataLabel.box ? 0 : (dataLabel.padding || 0); // Off left off = alignAttr.x + padding; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width - padding; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y + padding; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height - padding; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.drawDataLabels = function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel && point.visible) { // #407, #2510 halves[point.half].push(point); } }); /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, bottom, length = points.length, slotIndex; if (!length) { continue; } // Sort by angle series.sortByAngle(points, i - 0.5); // Assume equal label heights on either hemisphere (#2630) j = labelHeight = 0; while (!labelHeight && points[j]) { // #1569 labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968 j++; } // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // Build the slots bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight); for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) { slots.push(pos); } slotsLength = slots.length; /* Visualize the slots if (!series.slotElements) { series.slotElements = []; } if (i === 1) { series.slotElements.forEach(function (elem) { elem.destroy(); }); series.slotElements.length = 0; } slots.forEach(function (pos, no) { var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver', fill: 'rgba(0,0,255,0.1)' }) .add()); series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4) .attr({ fill: 'silver' }).add()); } }); // */ // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : 'inherit'; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = mathMin(mathMax(0, naturalY), chart.plotHeight); } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos && point.visible) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility //zIndex: 0 // #2722 (reversed) }) .add(series.dataLabelsGroup); } } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.placeDataLabels = function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel && point.visible) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; center[3] = Math.min(relativeLength(options.innerSize || 0, newSize), newSize); // #3632 this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var inverted = this.chart.inverted, series = point.series, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (inverted) { alignTo = { x: series.yAxis.len - alignTo.y - alignTo.height, y: series.xAxis.len - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }; } /** * Highcharts JS v4.1.9 (2015-10-07) * Highcharts module to hide overlapping data labels. This module is included by default in Highmaps. * * (c) 2010-2014 Torstein Honsi * * License: www.highcharts.com/license */ /*global Highcharts, HighchartsAdapter */ (function (H) { var Chart = H.Chart, each = H.each, pick = H.pick, addEvent = HighchartsAdapter.addEvent; // Collect potensial overlapping data labels. Stack labels probably don't need to be // considered because they are usually accompanied by data labels that lie inside the columns. Chart.prototype.callbacks.push(function (chart) { function collectAndHide() { var labels = []; each(chart.series, function (series) { var dlOptions = series.options.dataLabels, collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866 each(collections, function (coll) { each(series.points, function (point) { if (point[coll]) { point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118 labels.push(point[coll]); } }); }); } }); chart.hideOverlappingLabels(labels); } // Do it now ... collectAndHide(); // ... and after each chart redraw addEvent(chart, 'redraw', collectAndHide); }); /** * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth * visual imression. */ Chart.prototype.hideOverlappingLabels = function (labels) { var len = labels.length, label, i, j, label1, label2, isIntersecting, pos1, pos2, padding, intersectRect = function (x1, y1, w1, h1, x2, y2, w2, h2) { return !( x2 > x1 + w1 || x2 + w2 < x1 || y2 > y1 + h1 || y2 + h2 < y1 ); }; // Mark with initial opacity for (i = 0; i < len; i++) { label = labels[i]; if (label) { label.oldOpacity = label.opacity; label.newOpacity = 1; } } // Prevent a situation in a gradually rising slope, that each label // will hide the previous one because the previous one always has // lower rank. labels.sort(function (a, b) { return (b.labelrank || 0) - (a.labelrank || 0); }); // Detect overlapping labels for (i = 0; i < len; i++) { label1 = labels[i]; for (j = i + 1; j < len; ++j) { label2 = labels[j]; if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) { pos1 = label1.alignAttr; pos2 = label2.alignAttr; padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333) isIntersecting = intersectRect( pos1.x, pos1.y, label1.width - padding, label1.height - padding, pos2.x, pos2.y, label2.width - padding, label2.height - padding ); if (isIntersecting) { (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0; } } } } // Hide or show each(labels, function (label) { var complete, newOpacity; if (label) { newOpacity = label.newOpacity; if (label.oldOpacity !== newOpacity && label.placed) { // Make sure the label is completely hidden to avoid catching clicks (#4362) if (newOpacity) { label.show(true); } else { complete = function () { label.hide(); }; } // Animate or set the opacity label.alignAttr.opacity = newOpacity; label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete); } label.isOld = true; } }); }; }(Highcharts));/** * TrackerMixin for points and graphs */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; /* End TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) { var legend = this; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); legendItem.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { legendItem.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { if (item.setVisible) { item.setVisible(); } }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); }, createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item.series || item, 'checkboxClick', { // #3712 checked: target.checked, item: item }, function () { item.select(); } ); }); } }); /* * Add pointer cursor to legend itemstyle in defaultOptions */ defaultOptions.legend.itemStyle.cursor = 'pointer'; /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps var mousePos = e[isX ? 'chartX' : 'chartY'], axis = chart[isX ? 'xAxis' : 'yAxis'][0], startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange, goingLeft = startPos > mousePos; // #3613 if (axis.series.length && (goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) && (!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point * * @param {Object} e The event arguments * @param {Boolean} byProximity Falsy for kd points that are closest to the mouse, or to * actually hovered points. True for other points in shared tooltip. */ onMouseOver: function (e, byProximity) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; if (chart.hoverSeries !== series) { series.onMouseOver(); } // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } if (point.series) { // It may have been destroyed, #4130 // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); if (!byProximity) { chart.hoverPoint = point; } } }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; this.firePointEvent('mouseOut'); if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240 this.setState(); chart.hoverPoint = null; } }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state, move) { var point = this, plotX = mathFloor(point.plotX), // #4586 plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, halo = series.halo, haloOptions, newSymbol, pointAttr; state = state || NORMAL_STATE; // empty string pointAttr = point.pointAttr[state] || series.pointAttr[state]; if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr.r; point.graphic.attr(merge( pointAttr, radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 stateMarkerGraphic.element.point = point; // #4310 } } // Show me your halo haloOptions = stateOptions[state] && stateOptions[state].halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(chart.seriesGroup); } halo.attr(extend({ fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get() }, haloOptions.attributes))[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); } else if (halo) { halo.attr({ d: [] }); } point.state = state; }, haloPath: function (size) { var series = this.series, chart = series.chart, plotBox = series.getPlotBox(), inverted = chart.inverted; return chart.renderer.symbols.circle( plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size, plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; chart.hoverSeries = null; // #182, set to null before the mouseOut event fires // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, stateOptions = options.states, lineWidth = options.lineWidth, attribs, i = 0; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0); // #4035 } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); while (series['zoneGraph' + i]) { series['zoneGraph' + i].attr(attribs); i = i + 1; } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, drawTracker: TrackerMixin.drawTrackerGraph }); // global variables extend(Highcharts, { // Constructors Color: Color, Point: Point, Tick: Tick, Renderer: Renderer, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, error: error, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, map: map, merge: merge, splat: splat, extendClass: extendClass, pInt: pInt, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
src/components/Login/LoginItem.js
ascrutae/sky-walking-ui
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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, { Component } from 'react'; import PropTypes from 'prop-types'; import { Form, Button, Row, Col } from 'antd'; import omit from 'omit.js'; import styles from './index.less'; import map from './map'; const FormItem = Form.Item; function generator({ defaultProps, defaultRules, type }) { return (WrappedComponent) => { return class BasicComponent extends Component { static contextTypes = { form: PropTypes.object, updateActive: PropTypes.func, }; constructor(props) { super(props); this.state = { count: 0, }; } componentDidMount() { if (this.context.updateActive) { this.context.updateActive(this.props.name); } } componentWillUnmount() { clearInterval(this.interval); } onGetCaptcha = () => { let count = 59; this.setState({ count }); if (this.props.onGetCaptcha) { this.props.onGetCaptcha(); } this.interval = setInterval(() => { count -= 1; this.setState({ count }); if (count === 0) { clearInterval(this.interval); } }, 1000); }; render() { const { getFieldDecorator } = this.context.form; const options = {}; let otherProps = {}; const { onChange, defaultValue, rules, name, ...restProps } = this.props; const { count } = this.state; options.rules = rules || defaultRules; if (onChange) { options.onChange = onChange; } if (defaultValue) { options.initialValue = defaultValue; } otherProps = restProps || otherProps; if (type === 'Captcha') { const inputProps = omit(otherProps, ['onGetCaptcha']); return ( <FormItem> <Row gutter={8}> <Col span={16}> {getFieldDecorator(name, options)( <WrappedComponent {...defaultProps} {...inputProps} /> )} </Col> <Col span={8}> <Button disabled={count} className={styles.getCaptcha} size="large" onClick={this.onGetCaptcha} > {count ? `${count} s` : 'Get Verification code'} </Button> </Col> </Row> </FormItem> ); } return ( <FormItem> {getFieldDecorator(name, options)( <WrappedComponent {...defaultProps} {...otherProps} /> )} </FormItem> ); } }; }; } const LoginItem = {}; Object.keys(map).forEach((item) => { LoginItem[item] = generator({ defaultProps: map[item].props, defaultRules: map[item].rules, type: item, })(map[item].component); }); export default LoginItem;
client/components/Greetings/index.js
phytertek/mern-community
import React from 'react' const Greetings = React.createClass({ render() { return ( <div> Greetings </div> ) } }) export default Greetings
src/routes/login/Login.js
tonimoeckel/lap-counter-react
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Login.css'; class Login extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1> {this.props.title} </h1> <p className={s.lead}> Log in with your username or company email address. </p> <div className={s.formGroup}> <a className={s.facebook} href="/login/facebook"> <svg className={s.icon} width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" > <path d="M22 16l1-5h-5V7c0-1.544.784-2 3-2h2V0h-4c-4.072 0-7 2.435-7 7v4H7v5h5v14h6V16h4z" /> </svg> <span>Log in with Facebook</span> </a> </div> <div className={s.formGroup}> <a className={s.google} href="/login/google"> <svg className={s.icon} width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" > <path d={ 'M30 13h-4V9h-2v4h-4v2h4v4h2v-4h4m-15 2s-2-1.15-2-2c0 0-.5-1.828 1-3 ' + '1.537-1.2 3-3.035 3-5 0-2.336-1.046-5-3-6h3l2.387-1H10C5.835 0 2 3.345 2 7c0 ' + '3.735 2.85 6.56 7.086 6.56.295 0 .58-.006.86-.025-.273.526-.47 1.12-.47 1.735 ' + '0 1.037.817 2.042 1.523 2.73H9c-5.16 0-9 2.593-9 6 0 3.355 4.87 6 10.03 6 5.882 ' + '0 9.97-3 9.97-7 0-2.69-2.545-4.264-5-6zm-4-4c-2.395 0-5.587-2.857-6-6C4.587 ' + '3.856 6.607.93 9 1c2.394.07 4.603 2.908 5.017 6.052C14.43 10.195 13 13 11 ' + '13zm-1 15c-3.566 0-7-1.29-7-4 0-2.658 3.434-5.038 7-5 .832.01 2 0 2 0 1 0 ' + '2.88.88 4 2 1 1 1 2.674 1 3 0 3-1.986 4-7 4z' } /> </svg> <span>Log in with Google</span> </a> </div> <div className={s.formGroup}> <a className={s.twitter} href="/login/twitter"> <svg className={s.icon} width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" > <path d={ 'M30 6.708c-1.105.49-2.756 1.143-4 1.292 1.273-.762 2.54-2.56 ' + '3-4-.97.577-2.087 1.355-3.227 1.773L25 5c-1.12-1.197-2.23-2-4-2-3.398 0-6 ' + '2.602-6 6 0 .4.047.7.11.956L15 10C9 10 5.034 8.724 2 5c-.53.908-1 1.872-1 ' + '3 0 2.136 1.348 3.894 3 5-1.01-.033-2.17-.542-3-1 0 2.98 4.186 6.432 7 7-1 ' + '1-4.623.074-5 0 .784 2.447 3.31 3.95 6 4-2.105 1.648-4.647 2.51-7.53 2.51-.5 ' + '0-.988-.03-1.47-.084C2.723 27.17 6.523 28 10 28c11.322 0 17-8.867 17-17 ' + '0-.268.008-.736 0-1 1.2-.868 2.172-2.058 3-3.292z' } /> </svg> <span>Log in with Twitter</span> </a> </div> <strong className={s.lineThrough}>OR</strong> <form method="post"> <div className={s.formGroup}> <label className={s.label} htmlFor="usernameOrEmail"> Username or email address: </label> <input className={s.input} id="usernameOrEmail" type="text" name="usernameOrEmail" autoFocus // eslint-disable-line jsx-a11y/no-autofocus /> </div> <div className={s.formGroup}> <label className={s.label} htmlFor="password"> Password: </label> <input className={s.input} id="password" type="password" name="password" /> </div> <div className={s.formGroup}> <button className={s.button} type="submit"> Log in </button> </div> </form> </div> </div> ); } } export default withStyles(s)(Login);
client/src/views/InstanceDetail.js
petrleocompel/docker-dash
import React from 'react' import {responsr, instance, instanceStart, instanceStop, instanceRestart, instanceDelete} from "../api"; import Loader from "../Loader"; import {Button, Card, CardSubtitle, CardText, CardTitle, Col, Row} from "reactstrap"; import PropTypes from 'prop-types' Card.propTypes = { // Pass in a Component to override default element tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), inverse: PropTypes.bool, color: PropTypes.string, body: PropTypes.bool, className: PropTypes.string }; class InstanceDetail extends React.Component { state = {instance: null}; componentDidMount() { const {match: {params}} = this.props; instance(params.dockerId).then((data) => { this.setState({instance: data}); }) } //TODO vzhled render() { if (!this.state.instance) { return <Loader/> } return ( <Col xs="9" sm="6"> <Card> <CardTitle >Name: {this.state.instance.name}</CardTitle> <CardSubtitle>Status: {this.state.instance.status}</CardSubtitle> <CardText> <Row><Col>Instance id: {this.state.instance.id}</Col></Row> <Row><Col>Image: {this.state.instance.image}</Col></Row> <Row><Col>Image id: {this.state.instance.imageId}</Col></Row> <Row><Col>Created: {this.state.instance.created}</Col></Row> <Row><Col>Path: {this.state.instance.HostnamePath}</Col></Row> <Row><Col>Domain name: {this.state.instance.Domainname}</Col></Row> <Row><Col>Driver: {this.state.instance.driver}</Col></Row> <Row> <Col align="center"> <Button onClick={instanceStart(this.state.instance.id)} color="success">Start</Button>{' '} <Button onClick={instanceStop(this.state.instance.id)} color="danger">Stop</Button>{' '} <Button onClick={instanceRestart(this.state.instance.id)} color="warning">Restart</Button>{' '} <Button onClick={instanceDelete(this.state.instance.id)} color="secondary">Delete</Button> </Col> </Row> </CardText> </Card> </Col> ); } } export default InstanceDetail;
packages/generator-prismic-nextjs/generators/slicemachine/templates/pages/_app.js
prismicio/prismic-cli
// pages/_app.js import React from 'react' import NextApp from 'next/app' import { theme } from 'essential-slices'// this is new import { ThemeProvider, BaseStyles } from 'theme-ui' // this is new export default class App extends NextApp { render() { const { Component, pageProps } = this.props return ( <ThemeProvider theme={theme}> <BaseStyles> <Component {...pageProps} /> </BaseStyles> </ThemeProvider> ) } }
ajax/libs/react-native-web/0.0.0-da3429ed3/cjs/exports/useWindowDimensions/index.js
cdnjs/cdnjs
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * */ 'use strict'; exports.__esModule = true; exports.default = useWindowDimensions; var _Dimensions = _interopRequireDefault(require("../Dimensions")); var _react = require("react"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function useWindowDimensions() { var _useState = (0, _react.useState)(function () { return _Dimensions.default.get('window'); }), dims = _useState[0], setDims = _useState[1]; (0, _react.useEffect)(function () { function handleChange(_ref) { var window = _ref.window; // $FlowFixMe setDims(window); } _Dimensions.default.addEventListener('change', handleChange); // We might have missed an update between calling `get` in render and // `addEventListener` in this handler, so we set it here. If there was // no change, React will filter out this update as a no-op. setDims(_Dimensions.default.get('window')); return function () { _Dimensions.default.removeEventListener('change', handleChange); }; }, []); return dims; } module.exports = exports.default;
actor-apps/app-web/src/app/components/modals/create-group/Form.react.js
hmoraes/actor-platform
import _ from 'lodash'; import Immutable from 'immutable'; import keymirror from 'keymirror'; import React from 'react'; import { Styles, TextField, FlatButton } from 'material-ui'; import CreateGroupActionCreators from 'actions/CreateGroupActionCreators'; import ContactStore from 'stores/ContactStore'; import ContactItem from './ContactItem.react'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); const STEPS = keymirror({ NAME_INPUT: null, CONTACTS_SELECTION: null }); class CreateGroupForm extends React.Component { static displayName = 'CreateGroupForm' static childContextTypes = { muiTheme: React.PropTypes.object }; state = { step: STEPS.NAME_INPUT, selectedUserIds: new Immutable.Set() } getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ textField: { textColor: 'rgba(0,0,0,.87)', focusColor: '#68a3e7', backgroundColor: 'transparent', borderColor: '#68a3e7' } }); } render() { let stepForm; switch (this.state.step) { case STEPS.NAME_INPUT: stepForm = ( <form className="group-name" onSubmit={this.onNameSubmit}> <div className="modal-new__body"> <TextField className="login__form__input" floatingLabelText="Group name" fullWidth onChange={this.onNameChange} value={this.state.name}/> </div> <footer className="modal-new__footer text-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Add members" secondary={true} type="submit"/> </footer> </form> ); break; case STEPS.CONTACTS_SELECTION: let contactList = _.map(ContactStore.getContacts(), (contact, i) => { return ( <ContactItem contact={contact} key={i} onToggle={this.onContactToggle}/> ); }); stepForm = ( <form className="group-members" onSubmit={this.onMembersSubmit}> <div className="count">{this.state.selectedUserIds.size} Members</div> <div className="modal-new__body"> <ul className="contacts__list"> {contactList} </ul> </div> <footer className="modal-new__footer text-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Create group" secondary={true} type="submit"/> </footer> </form> ); break; } return stepForm; } onContactToggle = (contact, isSelected) => { if (isSelected) { this.setState({selectedUserIds: this.state.selectedUserIds.add(contact.uid)}); } else { this.setState({selectedUserIds: this.state.selectedUserIds.remove(contact.uid)}); } } onNameChange = event => { event.preventDefault(); this.setState({name: event.target.value}); } onNameSubmit = event => { event.preventDefault(); if (this.state.name) { let name = this.state.name.trim(); if (name.length > 0) { this.setState({step: STEPS.CONTACTS_SELECTION}); } } } onMembersSubmit =event => { event.preventDefault(); CreateGroupActionCreators.createGroup(this.state.name, null, this.state.selectedUserIds.toJS()); } } export default CreateGroupForm;
modules/__tests__/RouteComponent-test.js
ArmendGashi/react-router
/*eslint-env mocha */ import expect from 'expect' import React from 'react' import createHistory from 'history/lib/createMemoryHistory' import Router from '../Router' describe('a Route Component', function () { let node beforeEach(function () { node = document.createElement('div') }) afterEach(function () { React.unmountComponentAtNode(node) }) it('injects the right props', function (done) { const Parent = React.createClass({ componentDidMount() { assertProps(this.props) }, render() { return null } }) const Child = React.createClass({ render() { return null } }) const child = { path: 'child', component: Child } const parent = { path: '/', component: Parent, childRoutes: [ child ] } function assertProps(props) { expect(props.route).toEqual(parent) expect(props.routes).toEqual([parent, child]) } React.render(( <Router history={createHistory('/child')} routes={parent}/> ), node, done) }) })
app/components/Home.js
azlyth/redub
import fs from 'fs'; import path from 'path'; import React, { Component } from 'react'; import { remote } from 'electron'; import ReactPlayer from 'react-player'; import { Button } from 'react-bootstrap'; import { Scrollbars } from 'react-custom-scrollbars'; import ClipList from './ClipList'; import ProjectSelector from './ProjectSelector'; import * as u from '../utils'; import styles from './Home.css'; const DEFAULT_OUTPUT_PATH = path.join(remote.app.getPath('desktop'), 'masterpiece.mp4'); const PROGRESS_INTERVAL = 50; const PERCENT_MESSAGE = ` FYI, if the first clip is in the middle of the video, the progress will stay at zero for a bit. `; export default class Home extends Component { constructor(props) { super(props); this.state = { exporting: false, exportProgress: 0, videoPlaying: false, projectConfig: null, }; this.playVideo = this.playVideo.bind(this); this.stopIfPastEnd = this.stopIfPastEnd.bind(this); this.stopVideo = this.stopVideo.bind(this); this.export = this.export.bind(this); this.projectChosen = this.projectChosen.bind(this); this.updateExportProgress = this.updateExportProgress.bind(this); } componentDidMount() { u.setupFFBinaries(); } projectChosen(projectConfig) { this.setState({ projectConfig }); } workingOnProject() { return this.state.projectConfig !== null; } // start: integer time in seconds // end: integer time in seconds playVideo(start, end, withSound) { // Seek to the right time this.videoPlayer.seekTo(start); // Start the video and schedule its stop const volume = withSound ? 1.0 : 0; this.setState({ videoPlaying: true, volume, clipEnd: end }); } stopVideo() { this.setState({ videoPlaying: false, clipEnd: 0 }); } stopIfPastEnd(data) { if (data.playedSeconds > this.state.clipEnd) { this.stopVideo(); } } updateExportProgress(progress) { // Format the timestamp so that timeMs knows how to parse it const current = u.timeMs(`${progress.timemark.replace('.', ',')}0`); const start = u.timeMs(this.state.exportStartTime); const end = u.timeMs(this.state.exportEndTime); const percent = (current / (end - start)) * 100; this.setState({ exportProgress: Math.round(Number(percent)) }); } export() { const allClips = this.clipList.state.clips; // Find the indices of the clips that were dubbed let existingClips = fs.readdirSync(this.clipList.clipDirectory).filter(f => f[0] !== '.'); existingClips = existingClips.map(f => parseInt(f.replace('.webm', ''), 10)); existingClips.sort((a, b) => a - b); // Return if there are no clips to export if (existingClips.length === 0) { alert('You haven\'t dubbed anything yet!'); return; } // Get the actual clip that corresponds to each index const clips = existingClips.map(i => allClips[i]); // Get the first and last clips const exportStartTime = allClips[existingClips[0]].startTime; const exportEndTime = allClips[existingClips[existingClips.length - 1]].endTime; // Store the export info in our state this.setState({ exporting: true, exportProgress: 0, exportStartTime, exportEndTime, }); // Have the user choose where to output the video const outputPath = remote.dialog.showSaveDialog({ defaultPath: DEFAULT_OUTPUT_PATH }); // Add the clips to the video u.mergeAudio( this.state.projectConfig.video, clips, exportStartTime, exportEndTime, outputPath, this.updateExportProgress, ) .then(() => { this.setState({ exporting: false }); return 'success'; }) .catch(console.error); } renderHeader() { if (this.workingOnProject()) { return ( <ReactPlayer url={this.state.projectConfig.video} height="100%" width="100%" volume={this.state.volume} playing={this.state.videoPlaying} onProgress={this.stopIfPastEnd} progressFrequency={PROGRESS_INTERVAL} ref={(videoPlayer) => { this.videoPlayer = videoPlayer; }} /> ); } else { return ( <div className={styles.title}> <p>Redub</p> </div> ); } } renderBody() { if (this.workingOnProject()) { return ( <ClipList ref={(clipList) => { this.clipList = clipList; }} projectDirectory={this.state.projectConfig.projectDirectory} playVideo={this.playVideo} subtitleFile={this.state.projectConfig.subtitles} /> ); } return (<ProjectSelector onProjectChosen={this.projectChosen} />); } renderFooter() { if (this.workingOnProject()) { return ( <Button className={styles.exportButton} onClick={this.export} > EXPORT </Button> ); } } render() { return ( <div> {this.state.exporting && <div className={styles.exportOverlay}> <div> <p>Exporting your dank video...</p> <br /> <p>{this.state.exportProgress}%</p> <br /> <i className="fa fa-spinner fa-spin fa-2x" /> <br /> <br /> <p> {PERCENT_MESSAGE} </p> </div> </div> } <div className={styles.container} data-tid="container"> <div className={styles.header}> {this.renderHeader()} </div> <div className={styles.body}> <Scrollbars> {this.renderBody()} </Scrollbars> </div> <div className={styles.footer}> {this.renderFooter()} </div> </div> </div> ); } }
node_modules/react/lib/ReactDOMInput.js
Win-Myint/ReactChallenge2
/** * 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 = require('./ReactDOMIDOperations'); var LinkedValueUtils = require('./LinkedValueUtils'); var ReactMount = require('./ReactMount'); var ReactUpdates = require('./ReactUpdates'); var assign = require('./Object.assign'); var invariant = require('fbjs/lib/invariant'); 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 (process.env.NODE_ENV !== '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 ? process.env.NODE_ENV !== '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 ? process.env.NODE_ENV !== '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;
react-ui/src/components/presentation/TeamMatch.js
cajmyers/cydercup
import React, {Component} from 'react'; import SelectField from 'material-ui/SelectField'; class TeamMatch extends Component { render() { const style = { h1: { fontFamily: "Roboto", fontSize: 22, fontWeight: 500, marginTop: 15, marginBottom: 0, }, matchContainer: { width: "80%", margin: "auto", }, }; return ( <div style={style.matchContainer}> <h1 style={style.h1}> Match {this.props.matchNumber} </h1> <SelectField value={this.props.player1} fullWidth={true} onChange={this.props.selectPlayer1} maxHeight={200} > {this.props.players} </SelectField> <div> <span>and</span> </div> <SelectField value={this.props.player2} fullWidth={true} onChange={this.props.selectPlayer2} maxHeight={200} > {this.props.players} </SelectField> </div> ) } } export default TeamMatch;
src/public/components/toolbox/default.js
Harrns/segta
import React from 'react' import List from '@react-mdc/list' import classnames from 'classnames' import Color from '../../color' import { ThreeDotsIcon } from '../image/svg' export default class Toolbox extends React.Component { constructor (props) { super(props) this.state = { hover: false, hidden: true } this.initState(props) } initState (props) { Object.assign(this.state, {}) } componentWillReceiveProps (props) { this.initState(props) } open () { this.setState({ hidden: false }) } close () { this.setState({ hidden: true }) } switch () { this.setState({ hidden: !this.state.hidden }) } render () { const divStyle = Object.assign({}, style.div, this.state.hover ? style.divHover : {}) const listStyle = Object.assign({}, style.list, this.state.hidden ? style.listHidden : {}) return ( <div className="toolbox" id="file" style={divStyle} onMouseEnter={() => this.setState({ hover: true })} onMouseLeave={() => this.setState({ hover: false })} onClick={() => this.switch()}> <ThreeDotsIcon style={style.dots} /> <List className={classnames('toolbox-list', this.props.className)} id={this.props.id} style={listStyle} onMouseLeave={() => this.close()}> {this.props.children} </List> </div> ) } } const style = { div: { borderRadius: '100%', paddingTop: '2px', width: '30px', height: '28px', textAlign: 'center', transition: 'background-color 0.1s ease-in', cursor: 'pointer', marginTop: '-3px' }, divHover: { backgroundColor: Color.darkGrey }, dots: { fill: Color.white, verticalAlign: 'bottom' }, list: { position: 'relative', right: '115px', width: '150px', backgroundColor: Color.darkGrey, padding: '0px', borderRadius: '2px', boxShadow: '0px 11px 15px -7px rgba(0, 0, 0, 0.2), 0px 24px 38px 3px rgba(0, 0, 0, 0.14), 0px 9px 46px 8px rgba(0, 0, 0, 0.12)' }, listHidden: { visibility: 'hidden' } }
ajax/libs/react-redux/7.0.0-beta.1/react-redux.js
cdnjs/cdnjs
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('redux'), require('react-dom')) : typeof define === 'function' && define.amd ? define(['exports', 'react', 'redux', 'react-dom'], factory) : (global = global || self, factory(global.ReactRedux = {}, global.React, global.Redux, global.ReactDOM)); }(this, function (exports, React, redux, reactDom) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var reactIs_development = createCommonjsModule(function (module, exports) { { (function() { Object.defineProperty(exports, '__esModule', { value: true }); // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf; var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; function isValidElementType(type) { return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE); } /** * Forked from fbjs/warning: * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js * * Only change is we use console.warn instead of console.error, * and do nothing when 'console' is not supported. * This really simplifies the code. * --- * 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 lowPriorityWarning = function () {}; { var printWarning = function (format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.warn(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) {} }; lowPriorityWarning = function (condition, format) { if (format === undefined) { throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } var lowPriorityWarning$1 = lowPriorityWarning; function typeOf(object) { if (typeof object === 'object' && object !== null) { var $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type = object.type; switch (type) { case REACT_ASYNC_MODE_TYPE: case REACT_CONCURRENT_MODE_TYPE: case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: return type; default: var $$typeofType = type && type.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: case REACT_PORTAL_TYPE: return $$typeof; } } return undefined; } // AsyncMode is deprecated along with isAsyncMode var AsyncMode = REACT_ASYNC_MODE_TYPE; var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Lazy = REACT_LAZY_TYPE; var Memo = REACT_MEMO_TYPE; var Portal = REACT_PORTAL_TYPE; var Profiler = REACT_PROFILER_TYPE; var StrictMode = REACT_STRICT_MODE_TYPE; var Suspense = REACT_SUSPENSE_TYPE; var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated function isAsyncMode(object) { { if (!hasWarnedAboutDeprecatedIsAsyncMode) { hasWarnedAboutDeprecatedIsAsyncMode = true; lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.'); } } return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE; } function isConcurrentMode(object) { return typeOf(object) === REACT_CONCURRENT_MODE_TYPE; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isLazy(object) { return typeOf(object) === REACT_LAZY_TYPE; } function isMemo(object) { return typeOf(object) === REACT_MEMO_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } function isSuspense(object) { return typeOf(object) === REACT_SUSPENSE_TYPE; } exports.typeOf = typeOf; exports.AsyncMode = AsyncMode; exports.ConcurrentMode = ConcurrentMode; exports.ContextConsumer = ContextConsumer; exports.ContextProvider = ContextProvider; exports.Element = Element; exports.ForwardRef = ForwardRef; exports.Fragment = Fragment; exports.Lazy = Lazy; exports.Memo = Memo; exports.Portal = Portal; exports.Profiler = Profiler; exports.StrictMode = StrictMode; exports.Suspense = Suspense; exports.isValidElementType = isValidElementType; exports.isAsyncMode = isAsyncMode; exports.isConcurrentMode = isConcurrentMode; exports.isContextConsumer = isContextConsumer; exports.isContextProvider = isContextProvider; exports.isElement = isElement; exports.isForwardRef = isForwardRef; exports.isFragment = isFragment; exports.isLazy = isLazy; exports.isMemo = isMemo; exports.isPortal = isPortal; exports.isProfiler = isProfiler; exports.isStrictMode = isStrictMode; exports.isSuspense = isSuspense; })(); } }); unwrapExports(reactIs_development); var reactIs_development_1 = reactIs_development.typeOf; var reactIs_development_2 = reactIs_development.AsyncMode; var reactIs_development_3 = reactIs_development.ConcurrentMode; var reactIs_development_4 = reactIs_development.ContextConsumer; var reactIs_development_5 = reactIs_development.ContextProvider; var reactIs_development_6 = reactIs_development.Element; var reactIs_development_7 = reactIs_development.ForwardRef; var reactIs_development_8 = reactIs_development.Fragment; var reactIs_development_9 = reactIs_development.Lazy; var reactIs_development_10 = reactIs_development.Memo; var reactIs_development_11 = reactIs_development.Portal; var reactIs_development_12 = reactIs_development.Profiler; var reactIs_development_13 = reactIs_development.StrictMode; var reactIs_development_14 = reactIs_development.Suspense; var reactIs_development_15 = reactIs_development.isValidElementType; var reactIs_development_16 = reactIs_development.isAsyncMode; var reactIs_development_17 = reactIs_development.isConcurrentMode; var reactIs_development_18 = reactIs_development.isContextConsumer; var reactIs_development_19 = reactIs_development.isContextProvider; var reactIs_development_20 = reactIs_development.isElement; var reactIs_development_21 = reactIs_development.isForwardRef; var reactIs_development_22 = reactIs_development.isFragment; var reactIs_development_23 = reactIs_development.isLazy; var reactIs_development_24 = reactIs_development.isMemo; var reactIs_development_25 = reactIs_development.isPortal; var reactIs_development_26 = reactIs_development.isProfiler; var reactIs_development_27 = reactIs_development.isStrictMode; var reactIs_development_28 = reactIs_development.isSuspense; var reactIs = createCommonjsModule(function (module) { { module.exports = reactIs_development; } }); var reactIs_1 = reactIs.isValidElementType; var reactIs_2 = reactIs.isContextConsumer; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; var printWarning = function() {}; { var ReactPropTypesSecret$1 = ReactPropTypesSecret_1; var loggedTypeFailures = {}; var has = Function.call.bind(Object.prototype.hasOwnProperty); printWarning = function(text) { var message = 'Warning: ' + text; 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) {} }; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { { for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' ); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ); } 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 stack = getStack ? getStack() : ''; printWarning( 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') ); } } } } } /** * Resets warning cache when testing. * * @private */ checkPropTypes.resetWarningCache = function() { { loggedTypeFailures = {}; } }; var checkPropTypes_1 = checkPropTypes; var has$1 = Function.call.bind(Object.prototype.hasOwnProperty); var printWarning$1 = function() {}; { printWarning$1 = function(text) { var message = 'Warning: ' + text; 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) {} }; } function emptyFunctionThatReturnsNull() { return null; } var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), elementType: createElementTypeTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker, }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret_1) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package var err = new Error( 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); err.name = 'Invariant Violation'; throw err; } else if (typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { printWarning$1( 'You are manually calling a React.PropTypes validation ' + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunctionThatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createElementTypeTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!reactIs.isValidElementType(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { { if (arguments.length > 1) { printWarning$1( 'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' + 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).' ); } else { printWarning$1('Invalid argument supplied to oneOf, expected an array.'); } } return emptyFunctionThatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues, function replacer(key, value) { var type = getPreciseType(value); if (type === 'symbol') { return String(value); } return value; }); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (has$1(propValue, key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { printWarning$1('Invalid argument supplied to oneOfType, expected an instance of array.'); return emptyFunctionThatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { printWarning$1( 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.' ); return emptyFunctionThatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createStrictShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } // We need to check all keys in case some are required but missing from // props. var allKeys = objectAssign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (!checker) { return new PropTypeError( 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // falsy value can't be a Symbol if (!propValue) { return false; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes_1; ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var propTypes = createCommonjsModule(function (module) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ { var ReactIs = reactIs; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess); } }); var ReactReduxContext = React__default.createContext(null); // Default to a dummy "batch" implementation that just runs the callback function defaultNoopBatch(callback) { callback(); } var batch = defaultNoopBatch; // Allow injecting another batching function later var setBatch = function setBatch(newBatch) { return batch = newBatch; }; // Supply a getter just to skip dealing with ESM bindings var getBatch = function getBatch() { return batch; }; // well as nesting subscriptions of descendant components, so that we can ensure the // ancestor components re-render before descendants var CLEARED = null; var nullListeners = { notify: function notify() {} }; function createListenerCollection() { var batch = getBatch(); // the current/next pattern is copied from redux's createStore code. // TODO: refactor+expose that code to be reusable here? var current = []; var next = []; return { clear: function clear() { next = CLEARED; current = CLEARED; }, notify: function notify() { var listeners = current = next; batch(function () { for (var i = 0; i < listeners.length; i++) { listeners[i](); } }); }, get: function get() { return next; }, subscribe: function subscribe(listener) { var isSubscribed = true; if (next === current) next = current.slice(); next.push(listener); return function unsubscribe() { if (!isSubscribed || current === CLEARED) return; isSubscribed = false; if (next === current) next = current.slice(); next.splice(next.indexOf(listener), 1); }; } }; } var Subscription = /*#__PURE__*/ function () { function Subscription(store, parentSub) { this.store = store; this.parentSub = parentSub; this.unsubscribe = null; this.listeners = nullListeners; this.handleChangeWrapper = this.handleChangeWrapper.bind(this); } var _proto = Subscription.prototype; _proto.addNestedSub = function addNestedSub(listener) { this.trySubscribe(); return this.listeners.subscribe(listener); }; _proto.notifyNestedSubs = function notifyNestedSubs() { this.listeners.notify(); }; _proto.handleChangeWrapper = function handleChangeWrapper() { if (this.onStateChange) { this.onStateChange(); } }; _proto.isSubscribed = function isSubscribed() { return Boolean(this.unsubscribe); }; _proto.trySubscribe = function trySubscribe() { if (!this.unsubscribe) { this.unsubscribe = this.parentSub ? this.parentSub.addNestedSub(this.handleChangeWrapper) : this.store.subscribe(this.handleChangeWrapper); this.listeners = createListenerCollection(); } }; _proto.tryUnsubscribe = function tryUnsubscribe() { if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; this.listeners.clear(); this.listeners = nullListeners; } }; return Subscription; }(); var Provider = /*#__PURE__*/ function (_Component) { _inheritsLoose(Provider, _Component); function Provider(props) { var _this; _this = _Component.call(this, props) || this; var store = props.store; _this.notifySubscribers = _this.notifySubscribers.bind(_assertThisInitialized(_this)); var subscription = new Subscription(store); subscription.onStateChange = _this.notifySubscribers; _this.state = { store: store, subscription: subscription }; _this.previousState = store.getState(); return _this; } var _proto = Provider.prototype; _proto.componentDidMount = function componentDidMount() { this._isMounted = true; this.state.subscription.trySubscribe(); if (this.previousState !== this.props.store.getState()) { this.state.subscription.notifyNestedSubs(); } }; _proto.componentWillUnmount = function componentWillUnmount() { if (this.unsubscribe) this.unsubscribe(); this.state.subscription.tryUnsubscribe(); this._isMounted = false; }; _proto.componentDidUpdate = function componentDidUpdate(prevProps) { if (this.props.store !== prevProps.store) { this.state.subscription.tryUnsubscribe(); var subscription = new Subscription(this.props.store); subscription.onStateChange = this.notifySubscribers; this.setState({ store: this.props.store, subscription: subscription }); } }; _proto.notifySubscribers = function notifySubscribers() { this.state.subscription.notifyNestedSubs(); }; _proto.render = function render() { var Context = this.props.context || ReactReduxContext; return React__default.createElement(Context.Provider, { value: this.state }, this.props.children); }; return Provider; }(React.Component); Provider.propTypes = { store: propTypes.shape({ subscribe: propTypes.func.isRequired, dispatch: propTypes.func.isRequired, getState: propTypes.func.isRequired }), context: propTypes.object, children: propTypes.any }; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var REACT_STATICS = { childContextTypes: true, contextType: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromError: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var FORWARD_REF_STATICS = { '$$typeof': true, render: true, defaultProps: true, displayName: true, propTypes: true }; var MEMO_STATICS = { '$$typeof': true, compare: true, defaultProps: true, displayName: true, propTypes: true, type: true }; var TYPE_STATICS = {}; TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS; function getStatics(component) { if (reactIs.isMemo(component)) { return MEMO_STATICS; } return TYPE_STATICS[component['$$typeof']] || REACT_STATICS; } var defineProperty = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols$1 = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf = Object.getPrototypeOf; var objectPrototype = Object.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components if (objectPrototype) { var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } } var keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols$1) { keys = keys.concat(getOwnPropertySymbols$1(sourceComponent)); } var targetStatics = getStatics(targetComponent); var sourceStatics = getStatics(sourceComponent); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) { var descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) {} } } return targetComponent; } return targetComponent; } var hoistNonReactStatics_cjs = hoistNonReactStatics; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var invariant = function(condition, format, a, b, c, d, e, f) { { 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; } }; var invariant_1 = invariant; var EMPTY_ARRAY = []; var NO_SUBSCRIPTION_ARRAY = [null, null]; var stringifyComponent = function stringifyComponent(Comp) { try { return JSON.stringify(Comp); } catch (err) { return String(Comp); } }; function storeStateUpdatesReducer(state, action) { var updateCount = state[1]; return [action.payload, updateCount + 1]; } var initStateUpdates = function initStateUpdates() { return [null, 0]; }; // React currently throws a warning when using useLayoutEffect on the server. // To get around it, we can conditionally useEffect on the server (no-op) and // useLayoutEffect in the browser. We need useLayoutEffect because we want // `connect` to perform sync updates to a ref to save the latest props after // a render is actually committed to the DOM. var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect; function connectAdvanced( /* selectorFactory is a func that is responsible for returning the selector function used to compute new props from state, props, and dispatch. For example: export default connectAdvanced((dispatch, options) => (state, props) => ({ thing: state.things[props.thingId], saveThing: fields => dispatch(actionCreators.saveThing(props.thingId, fields)), }))(YourComponent) Access to dispatch is provided to the factory so selectorFactories can bind actionCreators outside of their selector as an optimization. Options passed to connectAdvanced are passed to the selectorFactory, along with displayName and WrappedComponent, as the second argument. Note that selectorFactory is responsible for all caching/memoization of inbound and outbound props. Do not use connectAdvanced directly without memoizing results between calls to your selector, otherwise the Connect component will re-render on every state or props change. */ selectorFactory, // options object: _ref) { if (_ref === void 0) { _ref = {}; } var _ref2 = _ref, _ref2$getDisplayName = _ref2.getDisplayName, getDisplayName = _ref2$getDisplayName === void 0 ? function (name) { return "ConnectAdvanced(" + name + ")"; } : _ref2$getDisplayName, _ref2$methodName = _ref2.methodName, methodName = _ref2$methodName === void 0 ? 'connectAdvanced' : _ref2$methodName, _ref2$renderCountProp = _ref2.renderCountProp, renderCountProp = _ref2$renderCountProp === void 0 ? undefined : _ref2$renderCountProp, _ref2$shouldHandleSta = _ref2.shouldHandleStateChanges, shouldHandleStateChanges = _ref2$shouldHandleSta === void 0 ? true : _ref2$shouldHandleSta, _ref2$storeKey = _ref2.storeKey, storeKey = _ref2$storeKey === void 0 ? 'store' : _ref2$storeKey, _ref2$withRef = _ref2.withRef, withRef = _ref2$withRef === void 0 ? false : _ref2$withRef, _ref2$forwardRef = _ref2.forwardRef, forwardRef = _ref2$forwardRef === void 0 ? false : _ref2$forwardRef, _ref2$context = _ref2.context, context = _ref2$context === void 0 ? ReactReduxContext : _ref2$context, connectOptions = _objectWithoutPropertiesLoose(_ref2, ["getDisplayName", "methodName", "renderCountProp", "shouldHandleStateChanges", "storeKey", "withRef", "forwardRef", "context"]); invariant_1(renderCountProp === undefined, "renderCountProp is removed. render counting is built into the latest React Dev Tools profiling extension"); invariant_1(!withRef, 'withRef is removed. To access the wrapped instance, use a ref on the connected component'); var customStoreWarningMessage = 'To use a custom Redux store for specific components, create a custom React context with ' + "React.createContext(), and pass the context object to React Redux's Provider and specific components" + ' like: <Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>. ' + 'You may also pass a {context : MyContext} option to connect'; invariant_1(storeKey === 'store', 'storeKey has been removed and does not do anything. ' + customStoreWarningMessage); var Context = context; return function wrapWithConnect(WrappedComponent) { { invariant_1(reactIs_1(WrappedComponent), "You must pass a component to the function returned by " + (methodName + ". Instead received " + stringifyComponent(WrappedComponent))); } var wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component'; var displayName = getDisplayName(wrappedComponentName); var selectorFactoryOptions = _extends({}, connectOptions, { getDisplayName: getDisplayName, methodName: methodName, renderCountProp: renderCountProp, shouldHandleStateChanges: shouldHandleStateChanges, storeKey: storeKey, displayName: displayName, wrappedComponentName: wrappedComponentName, WrappedComponent: WrappedComponent }); var pure = connectOptions.pure; function createChildSelector(store) { return selectorFactory(store.dispatch, selectorFactoryOptions); } // If we aren't running in "pure" mode, we don't want to memoize values. // To avoid conditionally calling hooks, we fall back to a tiny wrapper // that just executes the given callback immediately. var usePureOnlyMemo = pure ? React.useMemo : function (callback) { return callback(); }; function ConnectFunction(props) { var _useMemo = React.useMemo(function () { // Distinguish between actual "data" props that were passed to the wrapper component, // and values needed to control behavior (forwarded refs, alternate context instances). // To maintain the wrapperProps object reference, memoize this destructuring. var context = props.context, forwardedRef = props.forwardedRef, wrapperProps = _objectWithoutPropertiesLoose(props, ["context", "forwardedRef"]); return [context, forwardedRef, wrapperProps]; }, [props]), propsContext = _useMemo[0], forwardedRef = _useMemo[1], wrapperProps = _useMemo[2]; var ContextToUse = React.useMemo(function () { // Users may optionally pass in a custom context instance to use instead of our ReactReduxContext. // Memoize the check that determines which context instance we should use. return propsContext && propsContext.Consumer && reactIs_2(React__default.createElement(propsContext.Consumer, null)) ? propsContext : Context; }, [propsContext, Context]); // Retrieve the store and ancestor subscription via context, if available var contextValue = React.useContext(ContextToUse); // The store _must_ exist as either a prop or in context var didStoreComeFromProps = Boolean(props.store); var didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store); invariant_1(didStoreComeFromProps || didStoreComeFromContext, "Could not find \"store\" in the context of " + ("\"" + displayName + "\". Either wrap the root component in a <Provider>, ") + "or pass a custom React context provider to <Provider> and the corresponding " + ("React context consumer to " + displayName + " in connect options.")); var store = props.store || contextValue.store; var childPropsSelector = React.useMemo(function () { // The child props selector needs the store reference as an input. // Re-create this selector whenever the store changes. return createChildSelector(store); }, [store]); var _useMemo2 = React.useMemo(function () { if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY; // This Subscription's source should match where store came from: props vs. context. A component // connected to the store via props shouldn't use subscription from context, or vice versa. var subscription = new Subscription(store, didStoreComeFromProps ? null : contextValue.subscription); // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in // the middle of the notification loop, where `subscription` will then be null. This can // probably be avoided if Subscription's listeners logic is changed to not call listeners // that have been unsubscribed in the middle of the notification loop. var notifyNestedSubs = subscription.notifyNestedSubs.bind(subscription); return [subscription, notifyNestedSubs]; }, [store, didStoreComeFromProps, contextValue]), subscription = _useMemo2[0], notifyNestedSubs = _useMemo2[1]; // Determine what {store, subscription} value should be put into nested context, if necessary, // and memoize that value to avoid unnecessary context updates. var overriddenContextValue = React.useMemo(function () { if (didStoreComeFromProps) { // This component is directly subscribed to a store from props. // We don't want descendants reading from this store - pass down whatever // the existing context value is from the nearest connected ancestor. return contextValue; } // Otherwise, put this component's subscription instance into context, so that // connected descendants won't update until after this component is done return _extends({}, contextValue, { subscription: subscription }); }, [didStoreComeFromProps, contextValue, subscription]); // We need to force this wrapper component to re-render whenever a Redux store update // causes a change to the calculated child component props (or we caught an error in mapState) var _useReducer = React.useReducer(storeStateUpdatesReducer, EMPTY_ARRAY, initStateUpdates), _useReducer$ = _useReducer[0], previousStateUpdateResult = _useReducer$[0], forceComponentUpdateDispatch = _useReducer[1]; // Propagate any mapState/mapDispatch errors upwards if (previousStateUpdateResult && previousStateUpdateResult.error) { throw previousStateUpdateResult.error; } // Set up refs to coordinate values between the subscription effect and the render logic var lastChildProps = React.useRef(); var lastWrapperProps = React.useRef(wrapperProps); var childPropsFromStoreUpdate = React.useRef(); var actualChildProps = usePureOnlyMemo(function () { // Tricky logic here: // - This render may have been triggered by a Redux store update that produced new child props // - However, we may have gotten new wrapper props after that // If we have new child props, and the same wrapper props, we know we should use the new child props as-is. // But, if we have new wrapper props, those might change the child props, so we have to recalculate things. // So, we'll use the child props from store update only if the wrapper props are the same as last time. if (childPropsFromStoreUpdate.current && wrapperProps === lastWrapperProps.current) { return childPropsFromStoreUpdate.current; } // TODO We're reading the store directly in render() here. Bad idea? // This will likely cause Bad Things (TM) to happen in Concurrent Mode. // Note that we do this because on renders _not_ caused by store updates, we need the latest store state // to determine what the child props should be. return childPropsSelector(store.getState(), wrapperProps); }, [store, previousStateUpdateResult, wrapperProps]); // We need this to execute synchronously every time we re-render. However, React warns // about useLayoutEffect in SSR, so we try to detect environment and fall back to // just useEffect instead to avoid the warning, since neither will run anyway. useIsomorphicLayoutEffect(function () { // We want to capture the wrapper props and child props we used for later comparisons lastWrapperProps.current = wrapperProps; lastChildProps.current = actualChildProps; // If the render was from a store update, clear out that reference and cascade the subscriber update if (childPropsFromStoreUpdate.current) { childPropsFromStoreUpdate.current = null; notifyNestedSubs(); } }); // Our re-subscribe logic only runs when the store/subscription setup changes React.useEffect(function () { // If we're not subscribed to the store, nothing to do here if (!shouldHandleStateChanges) return; // Capture values for checking if and when this component unmounts var didUnsubscribe = false; var lastThrownError = null; // We'll run this callback every time a store subscription update propagates to this component var checkForUpdates = function checkForUpdates() { if (didUnsubscribe) { // Don't run stale listeners. // Redux doesn't guarantee unsubscriptions happen until next dispatch. return; } var latestStoreState = store.getState(); var newChildProps, error; try { // Actually run the selector with the most recent store state and wrapper props // to determine what the child props should be newChildProps = childPropsSelector(latestStoreState, lastWrapperProps.current); } catch (e) { error = e; lastThrownError = e; } if (!error) { lastThrownError = null; } // If the child props haven't changed, nothing to do here - cascade the subscription update if (newChildProps === lastChildProps.current) { notifyNestedSubs(); } else { // Save references to the new child props. Note that we track the "child props from store update" // as a ref instead of a useState/useReducer because we need a way to determine if that value has // been processed. If this went into useState/useReducer, we couldn't clear out the value without // forcing another re-render, which we don't want. lastChildProps.current = newChildProps; childPropsFromStoreUpdate.current = newChildProps; // If the child props _did_ change (or we caught an error), this wrapper component needs to re-render forceComponentUpdateDispatch({ type: 'STORE_UPDATED', payload: { latestStoreState: latestStoreState, error: error } }); } }; // Actually subscribe to the nearest connected ancestor (or store) subscription.onStateChange = checkForUpdates; subscription.trySubscribe(); // Pull data from the store after first render in case the store has // changed since we began. checkForUpdates(); var unsubscribeWrapper = function unsubscribeWrapper() { didUnsubscribe = true; subscription.tryUnsubscribe(); if (lastThrownError) { // It's possible that we caught an error due to a bad mapState function, but the // parent re-rendered without this component and we're about to unmount. // This shouldn't happen as long as we do top-down subscriptions correctly, but // if we ever do those wrong, this throw will surface the error in our tests. // In that case, throw the error from here so it doesn't get lost. throw lastThrownError; } }; return unsubscribeWrapper; }, [store, subscription, childPropsSelector]); // Now that all that's done, we can finally try to actually render the child component. // We memoize the elements for the rendered child component as an optimization. // If React sees the exact same element reference as last time, it bails out of re-rendering // that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate. var renderedChild = React.useMemo(function () { // Render the actual child component var renderedWrappedComponent = React__default.createElement(WrappedComponent, _extends({}, actualChildProps, { ref: forwardedRef })); if (shouldHandleStateChanges) { // If this component is subscribed to store updates, we need to pass its own // subscription instance down to our descendants. That means rendering the same // Context instance, and putting a different value into the context. return React__default.createElement(ContextToUse.Provider, { value: overriddenContextValue }, renderedWrappedComponent); } return renderedWrappedComponent; }, [ContextToUse, WrappedComponent, actualChildProps, forwardedRef, overriddenContextValue]); return renderedChild; } // If we're in "pure" mode, ensure our wrapper component only re-renders when incoming props have changed. var Connect = pure ? React__default.memo(ConnectFunction) : ConnectFunction; Connect.WrappedComponent = WrappedComponent; Connect.displayName = displayName; if (forwardRef) { var forwarded = React__default.forwardRef(function forwardConnectRef(props, ref) { return React__default.createElement(Connect, _extends({}, props, { forwardedRef: ref })); }); forwarded.displayName = displayName; forwarded.WrappedComponent = WrappedComponent; return hoistNonReactStatics_cjs(forwarded, WrappedComponent); } return hoistNonReactStatics_cjs(Connect, WrappedComponent); }; } var hasOwn = Object.prototype.hasOwnProperty; function is(x, y) { if (x === y) { return x !== 0 || y !== 0 || 1 / x === 1 / y; } else { return x !== x && y !== y; } } function shallowEqual(objA, objB) { if (is(objA, objB)) return true; if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) return false; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } /** * @param {any} obj The object to inspect. * @returns {boolean} True if the argument appears to be a plain object. */ function isPlainObject(obj) { if (typeof obj !== 'object' || obj === null) return false; var proto = Object.getPrototypeOf(obj); if (proto === null) return true; var baseProto = proto; while (Object.getPrototypeOf(baseProto) !== null) { baseProto = Object.getPrototypeOf(baseProto); } return proto === baseProto; } /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } function verifyPlainObject(value, displayName, methodName) { if (!isPlainObject(value)) { warning(methodName + "() in " + displayName + " must return a plain object. Instead received " + value + "."); } } function wrapMapToPropsConstant(getConstant) { return function initConstantSelector(dispatch, options) { var constant = getConstant(dispatch, options); function constantSelector() { return constant; } constantSelector.dependsOnOwnProps = false; return constantSelector; }; } // dependsOnOwnProps is used by createMapToPropsProxy to determine whether to pass props as args // to the mapToProps function being wrapped. It is also used by makePurePropsSelector to determine // whether mapToProps needs to be invoked when props have changed. // // A length of one signals that mapToProps does not depend on props from the parent component. // A length of zero is assumed to mean mapToProps is getting args via arguments or ...args and // therefore not reporting its length accurately.. function getDependsOnOwnProps(mapToProps) { return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1; } // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction, // this function wraps mapToProps in a proxy function which does several things: // // * Detects whether the mapToProps function being called depends on props, which // is used by selectorFactory to decide if it should reinvoke on props changes. // // * On first call, handles mapToProps if returns another function, and treats that // new function as the true mapToProps for subsequent calls. // // * On first call, verifies the first result is a plain object, in order to warn // the developer that their mapToProps function is not returning a valid result. // function wrapMapToPropsFunc(mapToProps, methodName) { return function initProxySelector(dispatch, _ref) { var displayName = _ref.displayName; var proxy = function mapToPropsProxy(stateOrDispatch, ownProps) { return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch); }; // allow detectFactoryAndVerify to get ownProps proxy.dependsOnOwnProps = true; proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) { proxy.mapToProps = mapToProps; proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps); var props = proxy(stateOrDispatch, ownProps); if (typeof props === 'function') { proxy.mapToProps = props; proxy.dependsOnOwnProps = getDependsOnOwnProps(props); props = proxy(stateOrDispatch, ownProps); } verifyPlainObject(props, displayName, methodName); return props; }; return proxy; }; } function whenMapDispatchToPropsIsFunction(mapDispatchToProps) { return typeof mapDispatchToProps === 'function' ? wrapMapToPropsFunc(mapDispatchToProps, 'mapDispatchToProps') : undefined; } function whenMapDispatchToPropsIsMissing(mapDispatchToProps) { return !mapDispatchToProps ? wrapMapToPropsConstant(function (dispatch) { return { dispatch: dispatch }; }) : undefined; } function whenMapDispatchToPropsIsObject(mapDispatchToProps) { return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? wrapMapToPropsConstant(function (dispatch) { return redux.bindActionCreators(mapDispatchToProps, dispatch); }) : undefined; } var defaultMapDispatchToPropsFactories = [whenMapDispatchToPropsIsFunction, whenMapDispatchToPropsIsMissing, whenMapDispatchToPropsIsObject]; function whenMapStateToPropsIsFunction(mapStateToProps) { return typeof mapStateToProps === 'function' ? wrapMapToPropsFunc(mapStateToProps, 'mapStateToProps') : undefined; } function whenMapStateToPropsIsMissing(mapStateToProps) { return !mapStateToProps ? wrapMapToPropsConstant(function () { return {}; }) : undefined; } var defaultMapStateToPropsFactories = [whenMapStateToPropsIsFunction, whenMapStateToPropsIsMissing]; function defaultMergeProps(stateProps, dispatchProps, ownProps) { return _extends({}, ownProps, stateProps, dispatchProps); } function wrapMergePropsFunc(mergeProps) { return function initMergePropsProxy(dispatch, _ref) { var displayName = _ref.displayName, pure = _ref.pure, areMergedPropsEqual = _ref.areMergedPropsEqual; var hasRunOnce = false; var mergedProps; return function mergePropsProxy(stateProps, dispatchProps, ownProps) { var nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps); if (hasRunOnce) { if (!pure || !areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps; } else { hasRunOnce = true; mergedProps = nextMergedProps; verifyPlainObject(mergedProps, displayName, 'mergeProps'); } return mergedProps; }; }; } function whenMergePropsIsFunction(mergeProps) { return typeof mergeProps === 'function' ? wrapMergePropsFunc(mergeProps) : undefined; } function whenMergePropsIsOmitted(mergeProps) { return !mergeProps ? function () { return defaultMergeProps; } : undefined; } var defaultMergePropsFactories = [whenMergePropsIsFunction, whenMergePropsIsOmitted]; function verify(selector, methodName, displayName) { if (!selector) { throw new Error("Unexpected value for " + methodName + " in " + displayName + "."); } else if (methodName === 'mapStateToProps' || methodName === 'mapDispatchToProps') { if (!selector.hasOwnProperty('dependsOnOwnProps')) { warning("The selector for " + methodName + " of " + displayName + " did not specify a value for dependsOnOwnProps."); } } } function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, displayName) { verify(mapStateToProps, 'mapStateToProps', displayName); verify(mapDispatchToProps, 'mapDispatchToProps', displayName); verify(mergeProps, 'mergeProps', displayName); } function impureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch) { return function impureFinalPropsSelector(state, ownProps) { return mergeProps(mapStateToProps(state, ownProps), mapDispatchToProps(dispatch, ownProps), ownProps); }; } function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, _ref) { var areStatesEqual = _ref.areStatesEqual, areOwnPropsEqual = _ref.areOwnPropsEqual, areStatePropsEqual = _ref.areStatePropsEqual; var hasRunAtLeastOnce = false; var state; var ownProps; var stateProps; var dispatchProps; var mergedProps; function handleFirstCall(firstState, firstOwnProps) { state = firstState; ownProps = firstOwnProps; stateProps = mapStateToProps(state, ownProps); dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); hasRunAtLeastOnce = true; return mergedProps; } function handleNewPropsAndNewState() { stateProps = mapStateToProps(state, ownProps); if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleNewProps() { if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps); if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleNewState() { var nextStateProps = mapStateToProps(state, ownProps); var statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps); stateProps = nextStateProps; if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleSubsequentCalls(nextState, nextOwnProps) { var propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps); var stateChanged = !areStatesEqual(nextState, state); state = nextState; ownProps = nextOwnProps; if (propsChanged && stateChanged) return handleNewPropsAndNewState(); if (propsChanged) return handleNewProps(); if (stateChanged) return handleNewState(); return mergedProps; } return function pureFinalPropsSelector(nextState, nextOwnProps) { return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps); }; } // TODO: Add more comments // If pure is true, the selector returned by selectorFactory will memoize its results, // allowing connectAdvanced's shouldComponentUpdate to return false if final // props have not changed. If false, the selector will always return a new // object and shouldComponentUpdate will always return true. function finalPropsSelectorFactory(dispatch, _ref2) { var initMapStateToProps = _ref2.initMapStateToProps, initMapDispatchToProps = _ref2.initMapDispatchToProps, initMergeProps = _ref2.initMergeProps, options = _objectWithoutPropertiesLoose(_ref2, ["initMapStateToProps", "initMapDispatchToProps", "initMergeProps"]); var mapStateToProps = initMapStateToProps(dispatch, options); var mapDispatchToProps = initMapDispatchToProps(dispatch, options); var mergeProps = initMergeProps(dispatch, options); { verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, options.displayName); } var selectorFactory = options.pure ? pureFinalPropsSelectorFactory : impureFinalPropsSelectorFactory; return selectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options); } /* connect is a facade over connectAdvanced. It turns its args into a compatible selectorFactory, which has the signature: (dispatch, options) => (nextState, nextOwnProps) => nextFinalProps connect passes its args to connectAdvanced as options, which will in turn pass them to selectorFactory each time a Connect component instance is instantiated or hot reloaded. selectorFactory returns a final props selector from its mapStateToProps, mapStateToPropsFactories, mapDispatchToProps, mapDispatchToPropsFactories, mergeProps, mergePropsFactories, and pure args. The resulting final props selector is called by the Connect component instance whenever it receives new props or store state. */ function match(arg, factories, name) { for (var i = factories.length - 1; i >= 0; i--) { var result = factories[i](arg); if (result) return result; } return function (dispatch, options) { throw new Error("Invalid value of type " + typeof arg + " for " + name + " argument when connecting component " + options.wrappedComponentName + "."); }; } function strictEqual(a, b) { return a === b; } // createConnect with default args builds the 'official' connect behavior. Calling it with // different options opens up some testing and extensibility scenarios function createConnect(_temp) { var _ref = _temp === void 0 ? {} : _temp, _ref$connectHOC = _ref.connectHOC, connectHOC = _ref$connectHOC === void 0 ? connectAdvanced : _ref$connectHOC, _ref$mapStateToPropsF = _ref.mapStateToPropsFactories, mapStateToPropsFactories = _ref$mapStateToPropsF === void 0 ? defaultMapStateToPropsFactories : _ref$mapStateToPropsF, _ref$mapDispatchToPro = _ref.mapDispatchToPropsFactories, mapDispatchToPropsFactories = _ref$mapDispatchToPro === void 0 ? defaultMapDispatchToPropsFactories : _ref$mapDispatchToPro, _ref$mergePropsFactor = _ref.mergePropsFactories, mergePropsFactories = _ref$mergePropsFactor === void 0 ? defaultMergePropsFactories : _ref$mergePropsFactor, _ref$selectorFactory = _ref.selectorFactory, selectorFactory = _ref$selectorFactory === void 0 ? finalPropsSelectorFactory : _ref$selectorFactory; return function connect(mapStateToProps, mapDispatchToProps, mergeProps, _ref2) { if (_ref2 === void 0) { _ref2 = {}; } var _ref3 = _ref2, _ref3$pure = _ref3.pure, pure = _ref3$pure === void 0 ? true : _ref3$pure, _ref3$areStatesEqual = _ref3.areStatesEqual, areStatesEqual = _ref3$areStatesEqual === void 0 ? strictEqual : _ref3$areStatesEqual, _ref3$areOwnPropsEqua = _ref3.areOwnPropsEqual, areOwnPropsEqual = _ref3$areOwnPropsEqua === void 0 ? shallowEqual : _ref3$areOwnPropsEqua, _ref3$areStatePropsEq = _ref3.areStatePropsEqual, areStatePropsEqual = _ref3$areStatePropsEq === void 0 ? shallowEqual : _ref3$areStatePropsEq, _ref3$areMergedPropsE = _ref3.areMergedPropsEqual, areMergedPropsEqual = _ref3$areMergedPropsE === void 0 ? shallowEqual : _ref3$areMergedPropsE, extraOptions = _objectWithoutPropertiesLoose(_ref3, ["pure", "areStatesEqual", "areOwnPropsEqual", "areStatePropsEqual", "areMergedPropsEqual"]); var initMapStateToProps = match(mapStateToProps, mapStateToPropsFactories, 'mapStateToProps'); var initMapDispatchToProps = match(mapDispatchToProps, mapDispatchToPropsFactories, 'mapDispatchToProps'); var initMergeProps = match(mergeProps, mergePropsFactories, 'mergeProps'); return connectHOC(selectorFactory, _extends({ // used in error messages methodName: 'connect', // used to compute Connect's displayName from the wrapped component's displayName. getDisplayName: function getDisplayName(name) { return "Connect(" + name + ")"; }, // if mapStateToProps is falsy, the Connect component doesn't subscribe to store state changes shouldHandleStateChanges: Boolean(mapStateToProps), // passed through to selectorFactory initMapStateToProps: initMapStateToProps, initMapDispatchToProps: initMapDispatchToProps, initMergeProps: initMergeProps, pure: pure, areStatesEqual: areStatesEqual, areOwnPropsEqual: areOwnPropsEqual, areStatePropsEqual: areStatePropsEqual, areMergedPropsEqual: areMergedPropsEqual }, extraOptions)); }; } var connect = createConnect(); /* eslint-disable import/no-unresolved */ setBatch(reactDom.unstable_batchedUpdates); exports.batch = reactDom.unstable_batchedUpdates; exports.Provider = Provider; exports.connectAdvanced = connectAdvanced; exports.ReactReduxContext = ReactReduxContext; exports.connect = connect; Object.defineProperty(exports, '__esModule', { value: true }); }));
src/components/store.js
AdinoyiSadiq/back-office-tool
import React from 'react'; import Inventory from './inventory'; import Cart from './cart'; class Store extends React.Component { render() { return ( <div className="content container"> <div className="row"> <Inventory carpets={this.props.carpets} juice={this.props.juice} addToCart={this.props.addToCart}/> <Cart carpets={this.props.carpets} juice={this.props.juice} cart={this.props.cart} addToOrder={this.props.addToOrder} removeFromCart={this.props.removeFromCart} clearCart={this.props.clearCart}/> </div> </div> ); } } export default Store;
skins/base/views/organisms/CreateRoom.js
Bitcoinsulting/vector-web
/* Copyright 2015 OpenMarket Ltd 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'; var React = require('react'); var CreateRoomController = require("../../../../src/controllers/organisms/CreateRoom"); var ComponentBroker = require('../../../../src/ComponentBroker'); var PresetValues = require('../../../../src/controllers/atoms/create_room/Presets').Presets; var CreateRoomButton = ComponentBroker.get("atoms/create_room/CreateRoomButton"); var RoomAlias = ComponentBroker.get("atoms/create_room/RoomAlias"); var Presets = ComponentBroker.get("atoms/create_room/Presets"); var UserSelector = ComponentBroker.get("molecules/UserSelector"); var RoomHeader = ComponentBroker.get("molecules/RoomHeader"); var Loader = require("react-loader"); module.exports = React.createClass({ displayName: 'CreateRoom', mixins: [CreateRoomController], getPreset: function() { return this.refs.presets.getPreset(); }, getName: function() { return this.refs.name_textbox.getName(); }, getTopic: function() { return this.refs.topic.getTopic(); }, getAliasLocalpart: function() { return this.refs.alias.getAliasLocalpart(); }, getInvitedUsers: function() { return this.refs.user_selector.getUserIds(); }, onPresetChanged: function(preset) { switch (preset) { case PresetValues.PrivateChat: this.setState({ preset: preset, is_private: true, share_history: false, }); break; case PresetValues.PublicChat: this.setState({ preset: preset, is_private: false, share_history: true, }); break; case PresetValues.Custom: this.setState({ preset: preset, }); break; } }, onPrivateChanged: function(ev) { this.setState({ preset: PresetValues.Custom, is_private: ev.target.checked, }); }, onShareHistoryChanged: function(ev) { this.setState({ preset: PresetValues.Custom, share_history: ev.target.checked, }); }, onTopicChange: function(ev) { this.setState({ topic: ev.target.value, }); }, onNameChange: function(ev) { this.setState({ room_name: ev.target.value, }); }, onInviteChanged: function(invited_users) { this.setState({ invited_users: invited_users, }); }, onAliasChanged: function(alias) { this.setState({ alias: alias }) }, onEncryptChanged: function(ev) { this.setState({ encrypt: ev.target.checked, }); }, render: function() { var curr_phase = this.state.phase; if (curr_phase == this.phases.CREATING) { return ( <Loader/> ); } else { var error_box = ""; if (curr_phase == this.phases.ERROR) { error_box = ( <div className="mx_Error"> An error occured: {this.state.error_string} </div> ); } return ( <div className="mx_CreateRoom"> <RoomHeader simpleHeader="Create room" /> <div className="mx_CreateRoom_body"> <input type="text" ref="room_name" value={this.state.room_name} onChange={this.onNameChange} placeholder="Name"/> <br /> <textarea className="mx_CreateRoom_description" ref="topic" value={this.state.topic} onChange={this.onTopicChange} placeholder="Topic"/> <br /> <RoomAlias ref="alias" alias={this.state.alias} onChange={this.onAliasChanged}/> <br /> <UserSelector ref="user_selector" selected_users={this.state.invited_users} onChange={this.onInviteChanged}/> <br /> <Presets ref="presets" onChange={this.onPresetChanged} preset={this.state.preset}/> <br /> <div> <label><input type="checkbox" ref="is_private" checked={this.state.is_private} onChange={this.onPrivateChanged}/> Make this room private</label> </div> <div> <label><input type="checkbox" ref="share_history" checked={this.state.share_history} onChange={this.onShareHistoryChanged}/> Share message history with new users</label> </div> <div className="mx_CreateRoom_encrypt"> <label><input type="checkbox" ref="encrypt" checked={this.state.encrypt} onChange={this.onEncryptChanged}/> Encrypt room</label> </div> <div> <CreateRoomButton onCreateRoom={this.onCreateRoom} /> <br /> </div> {error_box} </div> </div> ); } } });
src/svg-icons/maps/local-mall.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalMall = (props) => ( <SvgIcon {...props}> <path d="M19 6h-2c0-2.76-2.24-5-5-5S7 3.24 7 6H5c-1.1 0-1.99.9-1.99 2L3 20c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-7-3c1.66 0 3 1.34 3 3H9c0-1.66 1.34-3 3-3zm0 10c-2.76 0-5-2.24-5-5h2c0 1.66 1.34 3 3 3s3-1.34 3-3h2c0 2.76-2.24 5-5 5z"/> </SvgIcon> ); MapsLocalMall = pure(MapsLocalMall); MapsLocalMall.displayName = 'MapsLocalMall'; MapsLocalMall.muiName = 'SvgIcon'; export default MapsLocalMall;
packages/react-ui-core/src/ModalStack/__tests__/__helpers__/TestModal.js
rentpath/react-ui
import React from 'react' export default () => ( <div>This is a test modal</div> )
src/components/TimeAndSalary/common/withModal.js
goodjoblife/GoodJobShare
import React, { Component } from 'react'; export default (keyName = 'modal') => WrappedComponent => { class WithModal extends Component { state = { isOpen: false, }; setIsOpen = isOpen => { this.setState({ isOpen, }); }; render() { const props = { [keyName]: { isOpen: this.state.isOpen, setIsOpen: this.setIsOpen, }, ...this.props, }; return <WrappedComponent {...props} />; } } const displayName = WrappedComponent.displayName || WrappedComponent.name || 'Component'; WithModal.displayName = `withModal(${displayName})`; WithModal.fetchData = WrappedComponent.fetchData; return WithModal; };
client2/src/components/app.js
zhangbenny/Board
import React, { Component } from 'react'; import ColorPicker from 'react-color'; import ToggleDisplay from 'react-toggle-display'; import CanvasDraw from './canvasdraw'; import axios from 'axios'; import { Button } from 'react-bootstrap'; import { ButtonToolbar } from 'react-bootstrap'; import { ButtonGroup } from 'react-bootstrap'; import { DropdownButton } from 'react-bootstrap'; import { MenuItem } from 'react-bootstrap'; class App extends Component { constructor(props) { super(props); this.state = { toggleBGBox: 'Choose Background', toggleColorBox: 'Pick Color', brushColor: '#000000', lineWidth: 4, displayColorPicker: false, displayBGColorPicker: false, canvasStyle: { backgroundColor: '#FFFFFF' }, clear: false, restore: false }; this.showColorBox = this.showColorBox.bind(this); this.chooseColor = this.chooseColor.bind(this); this.showBGColorBox = this.showBGColorBox.bind(this) } eraser() { console.log(this.state.canvasStyle.backgroundColor); this.setState({ brushColor: this.state.canvasStyle.backgroundColor }) } increaseSize() { if (this.state.lineWidth<15){ this.setState({ lineWidth: this.state.lineWidth+=1 }); } } decreaseSize(){ if(this.state.lineWidth>1){ this.setState({ lineWidth: this.state.lineWidth-=1 }) } } handleOnClickClear() { this.setState({ restore: false, clear: true }); } showColorBox() { if(!this.state.displayColorPicker){ this.setState({ clear: false, displayColorPicker: !this.state.displayColorPicker, toggleColorBox: "Close Box" }); }else{ this.setState({ displayColorPicker: !this.state.displayColorPicker, toggleColorBox: "Pick Color" }); } } showBGColorBox() { if(!this.state.displayBGColorPicker) { this.setState({ clear: false, displayBGColorPicker: !this.state.displayBGColorPicker, toggleBGBox: "Close Box" }); } else { this.setState({ displayBGColorPicker: !this.state.displayBGColorPicker, toggleBGBox: "Choose Background" }); } } chooseBG(color) { let newstate = this.state; console.log(newstate) newstate.canvasStyle.backgroundColor = '#' + color.hex; newstate.clear = false; this.setState({ clear: false, newstate }); } chooseColor(color) { this.setState({brushColor: '#' + color.hex}) } saveAnImage () { let newCanvas = document.getElementById("canvas") let savedImage = new Image() savedImage.src = newCanvas.toDataURL('image/png') //console.log(savedImage.src); axios.post('/api/boards', { thing: savedImage.src }) .then(function (response) { console.log(response); //handleOnClickClear(); }) .catch(function (response) { console.log("ERROR saving"); console.log(response); }); } restoreBoard(){ this.setState({ clear: true, restore: true }); } render() { let popupPosition = { position: 'absolute', top: '12%', left: '5%', }; return ( <div> <h1>Frolicking Ampersand</h1> <div class = "row" className='button-bar' > <ButtonToolbar> <Button bsStyle = "primary" bsSize = "large" onClick={ this.handleOnClickClear.bind(this) }>Clear</Button> <Button bsStyle = "primary" bsSize = "large" onClick={ this.showColorBox }>{this.state.toggleColorBox}</Button> <Button bsStyle = "primary" bsSize = "large" onClick={ this.showBGColorBox }>{this.state.toggleBGBox}</Button> <Button bsStyle = "primary" bsSize = "large" onClick={this.saveAnImage}> Save </Button> <Button bsStyle = "primary" bsSize = "large" onClick={this.restoreBoard.bind(this)}> Restore </Button> <Button bsStyle = "primary" bsSize = "large" onClick={this.increaseSize.bind(this)}> thicker </Button> <Button bsStyle = "primary" bsSize = "large" onClick={this.decreaseSize.bind(this)}> thinner </Button> <Button bsStyle = "primary" bsSize = "large" onClick={this.eraser.bind(this)}> eraser </Button> </ButtonToolbar> </div> <div className='canvas-style'> <CanvasDraw {...this.state}/> </div> <ToggleDisplay show={this.state.displayColorPicker}> <ColorPicker type="sketch" positionCSS={ popupPosition } color={ this.state.brushColor } onChangeComplete={ this.chooseColor.bind(this) } /> </ToggleDisplay> <ToggleDisplay show={this.state.displayBGColorPicker}> <ColorPicker type="sketch" positionCSS={ popupPosition } color= {this.state.canvasStyle.backgroundColor} onChangeComplete={ this.chooseBG.bind(this) } /> </ToggleDisplay> </div> ) } }; export default App;
ajax/libs/rxjs/2.2.26/rx.lite.compat.js
dhowe/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 = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } 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(); }); }); }; function concatMap(selector) { return this.map(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } function concatMapObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return concatMap.call(this, selector); } return concatMap.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function selectMany(selector) { return this.select(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } function selectManyObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.select(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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 fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation){ event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch(event.type){ case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Node.js specific if (element.addListener) { element.addListener(name, handler); return disposableCreate(function () { element.removeListener(name, handler); }); } // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (typeof el.item === 'function' && typeof el.length === 'number') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * 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));
src/components/App.js
utage2002/mm
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import { IntlProvider } from 'react-intl'; import { Provider as ReduxProvider } from 'react-redux'; const ContextType = { // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader insertCss: PropTypes.func.isRequired, // Universal HTTP client fetch: PropTypes.func.isRequired, // Integrate Redux // http://redux.js.org/docs/basics/UsageWithReact.html ...ReduxProvider.childContextTypes, // Apollo Client client: PropTypes.object.isRequired, // ReactIntl intl: IntlProvider.childContextTypes.intl, }; /** * The top-level React component setting context (global) variables * that can be accessed from all the child components. * * https://facebook.github.io/react/docs/context.html * * Usage example: * * const context = { * history: createBrowserHistory(), * store: createStore(), * }; * * ReactDOM.render( * <App context={context}> * <Layout> * <LandingPage /> * </Layout> * </App>, * container, * ); */ class App extends React.PureComponent { static propTypes = { context: PropTypes.shape(ContextType).isRequired, children: PropTypes.element.isRequired, }; static childContextTypes = ContextType; getChildContext() { return this.props.context; } // NOTE: This methods are not needed if you update URL by setLocale action. // // componentDidMount() { // const store = this.props.context && this.props.context.store; // if (store) { // this.lastLocale = store.getState().intl.locale; // this.unsubscribe = store.subscribe(() => { // const state = store.getState(); // const { newLocale, locale } = state.intl; // if (!newLocale && this.lastLocale !== locale) { // this.lastLocale = locale; // this.forceUpdate(); // } // }); // } // } // // componentWillUnmount() { // if (this.unsubscribe) { // this.unsubscribe(); // this.unsubscribe = null; // } // } render() { return React.Children.only(this.props.children); } } export default App;
app/javascript/mastodon/features/report/comment.js
masto-donte-com-br/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, defineMessages, FormattedMessage } from 'react-intl'; import Button from 'mastodon/components/button'; import Toggle from 'react-toggle'; const messages = defineMessages({ placeholder: { id: 'report.placeholder', defaultMessage: 'Type or paste additional comments' }, }); export default @injectIntl class Comment extends React.PureComponent { static propTypes = { onSubmit: PropTypes.func.isRequired, comment: PropTypes.string.isRequired, onChangeComment: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, isSubmitting: PropTypes.bool, forward: PropTypes.bool, isRemote: PropTypes.bool, domain: PropTypes.string, onChangeForward: PropTypes.func.isRequired, }; handleClick = () => { const { onSubmit } = this.props; onSubmit(); }; handleChange = e => { const { onChangeComment } = this.props; onChangeComment(e.target.value); }; handleKeyDown = e => { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { this.handleClick(); } }; handleForwardChange = e => { const { onChangeForward } = this.props; onChangeForward(e.target.checked); }; render () { const { comment, isRemote, forward, domain, isSubmitting, intl } = this.props; return ( <React.Fragment> <h3 className='report-dialog-modal__title'><FormattedMessage id='report.comment.title' defaultMessage='Is there anything else you think we should know?' /></h3> <textarea className='report-dialog-modal__textarea' placeholder={intl.formatMessage(messages.placeholder)} value={comment} onChange={this.handleChange} onKeyDown={this.handleKeyDown} disabled={isSubmitting} /> {isRemote && ( <React.Fragment> <p className='report-dialog-modal__lead'><FormattedMessage id='report.forward_hint' defaultMessage='The account is from another server. Send an anonymized copy of the report there as well?' /></p> <label className='report-dialog-modal__toggle'> <Toggle checked={forward} disabled={isSubmitting} onChange={this.handleForwardChange} /> <FormattedMessage id='report.forward' defaultMessage='Forward to {target}' values={{ target: domain }} /> </label> </React.Fragment> )} <div className='flex-spacer' /> <div className='report-dialog-modal__actions'> <Button onClick={this.handleClick} disabled={isSubmitting}><FormattedMessage id='report.submit' defaultMessage='Submit report' /></Button> </div> </React.Fragment> ); } }
src/components/__tests__/ui/button-test.js
yursky/recommend
/** * Test to check if the component renders correctly */ /* global it expect */ import { Alert } from 'react-native'; import React from 'react'; import renderer from 'react-test-renderer'; import Button from '@ui/Button'; // Default Button Press function const onPress = () => Alert.alert('Hey Tester'); it('Button renders correctly', () => { const tree = renderer.create( <Button />, ).toJSON(); expect(tree).toMatchSnapshot(); }); it('Button with onPress renders correctly', () => { const tree = renderer.create( <Button onPress={onPress} />, ).toJSON(); expect(tree).toMatchSnapshot(); }); it('Button with Text renders correctly', () => { const tree = renderer.create( <Button onPress={onPress} title={'Test Button'} />, ).toJSON(); expect(tree).toMatchSnapshot(); }); it('Button with Icon renders correctly', () => { const tree = renderer.create( <Button onPress={onPress} icon={{ name: 'code' }} />, ).toJSON(); expect(tree).toMatchSnapshot(); }); it('Outlined Button renders correctly', () => { const tree = renderer.create( <Button onPress={onPress} outlined />, ).toJSON(); expect(tree).toMatchSnapshot(); }); it('Outlined Button with Icon renders correctly', () => { const tree = renderer.create( <Button onPress={onPress} outlined icon={{ name: 'code' }} />, ).toJSON(); expect(tree).toMatchSnapshot(); }); it('Small Button renders correctly', () => { const tree = renderer.create( <Button onPress={onPress} small />, ).toJSON(); expect(tree).toMatchSnapshot(); }); it('Small Button with Icon renders correctly', () => { const tree = renderer.create( <Button onPress={onPress} small icon={{ name: 'code' }} />, ).toJSON(); expect(tree).toMatchSnapshot(); }); it('Large Button renders correctly', () => { const tree = renderer.create( <Button onPress={onPress} small />, ).toJSON(); expect(tree).toMatchSnapshot(); }); it('Large Button with Icon renders correctly', () => { const tree = renderer.create( <Button onPress={onPress} large icon={{ name: 'code' }} />, ).toJSON(); expect(tree).toMatchSnapshot(); });
jrt/src/routes/home/index.js
wizzardo/jrtorrent
import React from 'react'; import './style.css'; import {DiskUsage} from "../../components/DiskUsage"; import {TorrentsList} from "../../components/TorrentsList"; import AddButton from "../../components/AddButton"; const Home = () => ( <div className='home'> <DiskUsage /> <TorrentsList/> <AddButton/> </div> ); export default Home;
generators/add/templates/react/component.js
HsuTing/generator-cat
'use strict'; import React from 'react'; import radium from 'radium'; import Wrapper from 'cat-components/lib/wrapper'; import Normalize from 'componentsShare/Normalize'; <% if(relay) { -%> import <%= componentName %>Container from 'containers/<%= componentName %>Container'; <% } -%> @radium class <%= componentName %> extends React.Component { render() { return ( <div> This is <%= componentName %>! <% if(relay) { -%> <<%= componentName %>Container /> <% } -%> </div> ); } } /* eslint-disable react/display-name, react/prop-types */ export default ({radiumConfig, ...props}) => ( <Wrapper radiumConfig={radiumConfig}> <div> <Normalize /> <<%= componentName %> {...props} /> </div> </Wrapper> ); /* eslint-enable react/display-name, react/prop-types */