diff --git a/TODO b/TODO index a430f46..35818b4 100644 --- a/TODO +++ b/TODO @@ -73,6 +73,7 @@ DONE Embeddable rxmarbles DONE Initial affordance animation in diagram TODO Fix affordance animation stuck for combineLatest +DONE Track and show individual subscriptions to input streams TODO Disambiguate simultaneous marbles Vertically spread them Change example takeLast(1) to takeLast(2) diff --git a/dist/js/app.js b/dist/js/app.js index 724e474..de6b6e6 100644 --- a/dist/js/app.js +++ b/dist/js/app.js @@ -51,7 +51,7 @@ process.nextTick = function (fun) { } } queue.push(new Item(fun, args)); - if (!draining) { + if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; @@ -12590,8 +12590,7 @@ module.exports={ "tarball": "http://registry.npmjs.org/rx/-/rx-2.5.2.tgz" }, "directories": {}, - "_resolved": "https://registry.npmjs.org/rx/-/rx-2.5.2.tgz", - "readme": "ERROR: No README data found!" + "_resolved": "https://registry.npmjs.org/rx/-/rx-2.5.2.tgz" } },{}],65:[function(require,module,exports){ @@ -12617,10 +12616,10 @@ module.exports = createAttribute; */ function createAttribute(name, value, isAttribute) { - var attrType = properties[name]; - if (attrType) { + if (properties.hasOwnProperty(name)) { if (shouldSkip(name, value)) return ''; name = (attributeNames[name] || name).toLowerCase(); + var attrType = properties[name]; // for BOOLEAN `value` only has to be truthy // for OVERLOADED_BOOLEAN `value` has to be === true if ((attrType === types.BOOLEAN) || @@ -12670,6 +12669,7 @@ var extend = require('xtend'); var isVNode = require('virtual-dom/vnode/is-vnode'); var isVText = require('virtual-dom/vnode/is-vtext'); var isThunk = require('virtual-dom/vnode/is-thunk'); +var isWidget = require('virtual-dom/vnode/is-widget'); var softHook = require('virtual-dom/virtual-hyperscript/hooks/soft-set-hook'); var attrHook = require('virtual-dom/virtual-hyperscript/hooks/attribute-hook'); var paramCase = require('param-case'); @@ -12685,6 +12685,10 @@ function toHTML(node, parent) { node = node.render(); } + if (isWidget(node) && node.render) { + node = node.render(); + } + if (isVNode(node)) { return openTag(node) + tagContent(node) + closeTag(node); } else if (isVText(node)) { @@ -12751,7 +12755,7 @@ function closeTag(node) { var tag = node.tagName.toLowerCase(); return voidElements[tag] ? '' : ''; } -},{"./create-attribute":65,"./void-elements":76,"escape-html":67,"param-case":73,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":95,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":97,"virtual-dom/vnode/is-thunk":103,"virtual-dom/vnode/is-vnode":105,"virtual-dom/vnode/is-vtext":106,"xtend":74}],67:[function(require,module,exports){ +},{"./create-attribute":65,"./void-elements":76,"escape-html":67,"param-case":73,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":95,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":97,"virtual-dom/vnode/is-thunk":103,"virtual-dom/vnode/is-vnode":105,"virtual-dom/vnode/is-vtext":106,"virtual-dom/vnode/is-widget":107,"xtend":74}],67:[function(require,module,exports){ /** * Escape special characters in the given string of html. * @@ -16472,19 +16476,24 @@ function appendPatch(apply, patch) { // begin or end will be NaN if they were provided as negative numbers and // this iterable's size is unknown. In that case, cache first so there is - // a known size. + // a known size and these do not resolve to NaN. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys); } - var sliceSize = resolvedEnd - resolvedBegin; - if (sliceSize < 0) { - sliceSize = 0; + // Note: resolvedEnd is undefined when the original sequence's length is + // unknown and this slice did not supply an end and should contain all + // elements after resolvedBegin. + // In that case, resolvedSize will be NaN and sliceSize will remain undefined. + var resolvedSize = resolvedEnd - resolvedBegin; + var sliceSize; + if (resolvedSize === resolvedSize) { + sliceSize = resolvedSize < 0 ? 0 : resolvedSize; } var sliceSeq = makeSequence(iterable); - sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined; + sliceSeq.size = sliceSize; if (!useKeys && isSeq(iterable) && sliceSize >= 0) { sliceSeq.get = function (index, notSetValue) { @@ -16516,11 +16525,11 @@ function appendPatch(apply, patch) { }; sliceSeq.__iteratorUncached = function(type, reverse) { - if (sliceSize && reverse) { + if (sliceSize !== 0 && reverse) { return this.cacheResult().__iterator(type, reverse); } // Don't bother instantiating parent iterator if taking 0. - var iterator = sliceSize && iterable.__iterator(type, reverse); + var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse); var skipped = 0; var iterations = 0; return new src_Iterator__Iterator(function() { @@ -17016,7 +17025,13 @@ function appendPatch(apply, patch) { }; src_Map__Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); - return this.updateIn(keyPath, emptyMap(), function(m ) {return m.merge.apply(m, iters)}); + return this.updateIn( + keyPath, + emptyMap(), + function(m ) {return typeof m.merge === 'function' ? + m.merge.apply(m, iters) : + iters[iters.length - 1]} + ); }; src_Map__Map.prototype.mergeDeep = function(/*...iters*/) { @@ -17028,7 +17043,13 @@ function appendPatch(apply, patch) { }; src_Map__Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); - return this.updateIn(keyPath, emptyMap(), function(m ) {return m.mergeDeep.apply(m, iters)}); + return this.updateIn( + keyPath, + emptyMap(), + function(m ) {return typeof m.mergeDeep === 'function' ? + m.mergeDeep.apply(m, iters) : + iters[iters.length - 1]} + ); }; src_Map__Map.prototype.sort = function(comparator) { @@ -18191,7 +18212,7 @@ function appendPatch(apply, patch) { var newLevel = list._level; var newRoot = list._root; - // New origin might require creating a higher root. + // New origin might need creating a higher root. var offsetShift = 0; while (newOrigin + offsetShift < 0) { newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner); @@ -18208,7 +18229,7 @@ function appendPatch(apply, patch) { var oldTailOffset = getTailOffset(oldCapacity); var newTailOffset = getTailOffset(newCapacity); - // New size might require creating a higher root. + // New size might need creating a higher root. while (newTailOffset >= 1 << (newLevel + SHIFT)) { newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); newLevel += SHIFT; @@ -20109,6 +20130,7 @@ module.exports={ "preinstall": "rm -rf build && rm -rf node_modules && mkdir -p ignore/es5src", "postinstall": "ln -s ../ignore/es5src node_modules/rxmarbles && ln -s ../package.json node_modules/package.json", "less": "lessc styles/main.less dist/css/main.css", + "babel-run": "babel src --out-dir ignore/es5src", "babel": "mkdir -p ignore/es5src && babel src --out-dir ignore/es5src", "browserify": "browserify -e ignore/es5src/app.js --outfile dist/js/app.js", "browserify-element": "browserify -e ignore/es5src/element.js --outfile dist/js/element.js", @@ -20127,139 +20149,10864 @@ module.exports={ } },{}],116:[function(require,module,exports){ -arguments[4][63][0].apply(exports,arguments) -},{"_process":2,"dup":63}],117:[function(require,module,exports){ -'use strict'; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - -var _cyclejs = require('cyclejs'); - -var _cyclejs2 = _interopRequireDefault(_cyclejs); - -var Rx = _cyclejs2['default'].Rx; -var packageJson = require('package'); -var RxPackageJson = require('cyclejs/node_modules/rx/package.json'); - -var DEFAULT_EXAMPLE = 'merge'; +(function (process,global){ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { -module.exports = function appModel() { - return { - route$: Rx.Observable.fromEvent(window, 'hashchange').map(function (hashEvent) { - return hashEvent.target.location.hash.replace('#', ''); - }).startWith(window.location.hash.replace('#', '') || DEFAULT_EXAMPLE), - appVersion$: Rx.Observable.just(packageJson.version), - rxVersion$: Rx.Observable.just(RxPackageJson.version) + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false }; -}; -},{"cyclejs":5,"cyclejs/node_modules/rx/package.json":64,"package":115}],118:[function(require,module,exports){ -'use strict'; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - -var _cyclejs = require('cyclejs'); - -var _cyclejs2 = _interopRequireDefault(_cyclejs); + 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; -var _rxmarblesStylesColors = require('rxmarbles/styles/colors'); + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } -var _rxmarblesStylesColors2 = _interopRequireDefault(_rxmarblesStylesColors); + var Rx = { + internals: {}, + config: { + Promise: root.Promise + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }, + isFunction = Rx.helpers.isFunction = (function () { -var _rxmarblesStylesDimens = require('rxmarbles/styles/dimens'); + var isFn = function (value) { + return typeof value == 'function' || false; + } -var _rxmarblesStylesDimens2 = _interopRequireDefault(_rxmarblesStylesDimens); + // fallback for older versions of Chrome and Safari + if (isFn(/x/)) { + isFn = function(value) { + return typeof value == 'function' && toString.call(value) == '[object Function]'; + }; + } -var _rxmarblesStylesFonts = require('rxmarbles/styles/fonts'); + return isFn; + }()); -var _rxmarblesStylesFonts2 = _interopRequireDefault(_rxmarblesStylesFonts); + function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} + + Rx.config.longStackSupport = false; + var hasStacks = false; + try { + throw new Error(); + } catch (e) { + hasStacks = !!e.stack; + } -var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + // All code after this point will be filtered from stack traces reported by RxJS + var rStartingLine = captureLine(), rFileName; + + var STACK_JUMP_SEPARATOR = "From previous event:"; -var Rx = _cyclejs2['default'].Rx; -var h = _cyclejs2['default'].h; + function makeStackTraceLong(error, observable) { + // If possible, transform the error stack trace by removing Node and RxJS + // cruft, then concatenating with the stack trace of `observable`. + if (hasStacks && + observable.stack && + typeof error === "object" && + error !== null && + error.stack && + error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 + ) { + var stacks = []; + for (var o = observable; !!o; o = o.source) { + if (o.stack) { + stacks.unshift(o.stack); + } + } + stacks.unshift(error.stack); -var rxmarblesGithubUrl = 'https://github.com/staltz/rxmarbles'; -var rxjsGithubUrl = 'https://github.com/Reactive-Extensions/RxJS'; + var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); + error.stack = filterStackString(concatedStacks); + } + } -var pageRowWidth = '1060px'; -var sandboxWidth = '820px'; + function filterStackString(stackString) { + var lines = stackString.split("\n"), + desiredLines = []; + for (var i = 0, len = lines.length; i < len; i++) { + var line = lines[i]; -var pageRowStyle = { - position: 'relative', - width: pageRowWidth, - margin: '0 auto' -}; + if (!isInternalFrame(line) && !isNodeFrame(line) && line) { + desiredLines.push(line); + } + } + return desiredLines.join("\n"); + } -var pageRowChildStyle = { - display: 'inline-block', - marginLeft: '-' + _rxmarblesStylesDimens2['default'].spaceMedium -}; + function isInternalFrame(stackLine) { + var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); + if (!fileNameAndLineNumber) { + return false; + } + var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; -var pageRowFirstChildStyle = _rxmarblesStylesUtils.mergeStyles(pageRowChildStyle, { - width: 'calc(' + pageRowWidth + ' - ' + sandboxWidth + ' - ' + _rxmarblesStylesDimens2['default'].spaceMedium + ')', - marginRight: _rxmarblesStylesDimens2['default'].spaceMedium -}); + return fileName === rFileName && + lineNumber >= rStartingLine && + lineNumber <= rEndingLine; + } -var pageRowLastChildStyle = _rxmarblesStylesUtils.mergeStyles(pageRowChildStyle, { - width: sandboxWidth -}); + function isNodeFrame(stackLine) { + return stackLine.indexOf("(module.js:") !== -1 || + stackLine.indexOf("(node.js:") !== -1; + } -function vrenderHeader() { - return h('div', { style: pageRowStyle }, [h('h1', { style: _rxmarblesStylesUtils.mergeStyles({ - fontFamily: _rxmarblesStylesFonts2['default'].fontSpecial, - color: _rxmarblesStylesColors2['default'].greyDark }, pageRowFirstChildStyle) }, 'RxMarbles'), h('h3', { style: _rxmarblesStylesUtils.mergeStyles({ - color: _rxmarblesStylesColors2['default'].greyDark }, pageRowLastChildStyle) }, 'Interactive diagrams of Rx Observables')]); -} + function captureLine() { + if (!hasStacks) { return; } -function vrenderContent(route) { - return h('div', { style: _rxmarblesStylesUtils.mergeStyles(pageRowStyle, { marginTop: _rxmarblesStylesDimens2['default'].spaceSmall }) }, [h('div', { style: pageRowFirstChildStyle }, h('x-operators-menu', { key: 'operatorsMenu' })), h('div', { style: _rxmarblesStylesUtils.mergeStyles({ - position: 'absolute', - top: '0' }, pageRowLastChildStyle) }, h('x-sandbox', { key: 'sandbox', route: route, width: '820px' }))]); -} + try { + throw new Error(); + } catch (e) { + var lines = e.stack.split("\n"); + var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; + var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); + if (!fileNameAndLineNumber) { return; } -function vrenderFooter(appVersion, rxVersion) { - return h('section', { - style: { - position: 'fixed', - bottom: '2px', - right: _rxmarblesStylesDimens2['default'].spaceMedium, - color: _rxmarblesStylesColors2['default'].greyDark + rFileName = fileNameAndLineNumber[0]; + return fileNameAndLineNumber[1]; } - }, [h('a', { href: '' + rxmarblesGithubUrl + '/releases/tag/v' + appVersion }, 'v' + appVersion), ' built on ', h('a', { href: '' + rxjsGithubUrl + '/tree/v' + rxVersion }, 'RxJS v' + rxVersion), ' by ', h('a', { href: 'https://twitter.com/andrestaltz' }, '@andrestaltz')]); -} - -module.exports = function appView(model) { - return Rx.Observable.combineLatest(model.route$, model.appVersion$, model.rxVersion$, function (route, appVersion, rxVersion) { - return h('div', [vrenderHeader(), vrenderContent(route), vrenderFooter(appVersion, rxVersion)]); - }); -}; -},{"cyclejs":5,"rxmarbles/styles/colors":138,"rxmarbles/styles/dimens":139,"rxmarbles/styles/fonts":140,"rxmarbles/styles/utils":141}],119:[function(require,module,exports){ -'use strict'; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + function getFileNameAndLineNumber(stackLine) { + // Named functions: "at functionName (filename:lineNumber:columnNumber)" + var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); + if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } -var _cyclejs = require('cyclejs'); + // Anonymous functions: "at filename:lineNumber:columnNumber" + var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); + if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } -var _cyclejs2 = _interopRequireDefault(_cyclejs); + // Firefox style: "function@filename:lineNumber or @filename:lineNumber" + var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); + if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } + } + + var EmptyError = Rx.EmptyError = function() { + this.message = 'Sequence contains no elements.'; + Error.call(this); + }; + EmptyError.prototype = Error.prototype; -var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + var ObjectDisposedError = Rx.ObjectDisposedError = function() { + this.message = 'Object has been disposed'; + Error.call(this); + }; + ObjectDisposedError.prototype = Error.prototype; -var Rx = _cyclejs2['default'].Rx; -var h = _cyclejs2['default'].h; + var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { + this.message = 'Argument out of range'; + Error.call(this); + }; + ArgumentOutOfRangeError.prototype = Error.prototype; -function createContainerStyle(inputStyle) { - return { - display: 'inline-block', - position: 'relative', - width: 'calc(8 * ' + inputStyle.thickness + ')', - height: inputStyle.height, - margin: '0 calc(-4 * ' + inputStyle.thickness + ')' + var NotSupportedError = Rx.NotSupportedError = function (message) { + this.message = message || 'This operation is not supported'; + Error.call(this); }; -} + NotSupportedError.prototype = Error.prototype; -function createInnerStyle(inputStyle) { - return { - width: inputStyle.thickness, + var NotImplementedError = Rx.NotImplementedError = function (message) { + this.message = message || 'This operation is not implemented'; + Error.call(this); + }; + NotImplementedError.prototype = Error.prototype; + + var notImplemented = Rx.helpers.notImplemented = function () { + throw new NotImplementedError(); + }; + + var notSupported = Rx.helpers.notSupported = function () { + throw new NotSupportedError(); + }; + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; + + var isIterable = Rx.helpers.isIterable = function (o) { + return o[$iterator$] !== undefined; + } + + var isArrayLike = Rx.helpers.isArrayLike = function (o) { + return o && o.length !== undefined; + } + + Rx.helpers.iterator = $iterator$; + + var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { + if (typeof thisArg === 'undefined') { return func; } + switch(argCount) { + case 0: + return function() { + return func.call(thisArg) + }; + case 1: + return function(arg) { + return func.call(thisArg, arg); + } + case 2: + return function(value, index) { + return func.call(thisArg, value, index); + }; + case 3: + return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + } + + return function() { + return func.apply(thisArg, arguments); + }; + }; + + /** Used to determine if values are of the language type Object */ + var dontEnums = ['toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor'], + dontEnumsLength = dontEnums.length; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + + var hasProp = {}.hasOwnProperty, + slice = Array.prototype.slice; + + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + var addProperties = Rx.internals.addProperties = function (obj) { + for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } + for (var idx = 0, ln = sources.length; idx < ln; idx++) { + var source = sources[idx]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + var errorObj = {e: {}}; + var tryCatchTarget; + function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } + } + function tryCatch(fn) { + if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } + tryCatchTarget = fn; + return tryCatcher; + } + function thrower(e) { + throw e; + } + + // Collections + function IndexedItem(id, value) { + this.id = id; + this.value = value; + } + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + c === 0 && (c = this.id - other.id); + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { return; } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { return; } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + +index || (index = 0); + if (index >= this.length || index < 0) { return; } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + this.items[this.length] = undefined; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + var args = [], i, len; + if (Array.isArray(arguments[0])) { + args = arguments[0]; + len = args.length; + } else { + len = arguments.length; + args = new Array(len); + for(i = 0; i < len; i++) { args[i] = arguments[i]; } + } + for(i = 0; i < len; i++) { + if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } + } + this.disposables = args; + this.isDisposed = false; + this.length = args.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var len = this.disposables.length, currentDisposables = new Array(len); + for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } + this.disposables = []; + this.length = 0; + + for (i = 0; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Provides a set of static methods for creating Disposables. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + /** + * Validates whether the given object is a disposable + * @param {Object} Object to test whether it has a dispose method + * @returns {Boolean} true if a disposable object, else false. + */ + var isDisposable = Disposable.isDisposable = function (d) { + return d && isFunction(d.dispose); + }; + + var checkDisposed = Disposable.checkDisposed = function (disposable) { + if (disposable.isDisposed) { throw new ObjectDisposedError(); } + }; + + // Single assignment + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { + this.isDisposed = false; + this.current = null; + }; + SingleAssignmentDisposable.prototype.getDisposable = function () { + return this.current; + }; + SingleAssignmentDisposable.prototype.setDisposable = function (value) { + if (this.current) { throw new Error('Disposable has already been assigned'); } + var shouldDispose = this.isDisposed; + !shouldDispose && (this.current = value); + shouldDispose && value && value.dispose(); + }; + SingleAssignmentDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + // Multiple assignment disposable + var SerialDisposable = Rx.SerialDisposable = function () { + this.isDisposed = false; + this.current = null; + }; + SerialDisposable.prototype.getDisposable = function () { + return this.current; + }; + SerialDisposable.prototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed; + if (!shouldDispose) { + var old = this.current; + this.current = value; + } + old && old.dispose(); + shouldDispose && value && value.dispose(); + }; + SerialDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed && !this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed && !this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + function scheduleItem(s, self) { + if (!self.isDisposed) { + self.isDisposed = true; + self.disposable.dispose(); + } + } + + ScheduledDisposable.prototype.dispose = function () { + this.scheduler.scheduleWithState(this, scheduleItem); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + /** Determines whether the given object is a scheduler */ + Scheduler.isScheduler = function (s) { + return s instanceof Scheduler; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + timeSpan < 0 && (timeSpan = 0); + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler; + + (function (schedulerProto) { + + function invokeRecImmediate(scheduler, pair) { + var state = pair[0], action = pair[1], group = new CompositeDisposable(); + + function recursiveAction(state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + } + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair[0], action = pair[1], group = new CompositeDisposable(); + function recursiveAction(state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function scheduleInnerRecursive(action, self) { + action(function(dt) { self(action, dt); }); + } + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState([state, action], invokeRecImmediate); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative([state, action], dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute([state, action], dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, action); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { + if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } + period = normalizeTime(period); + var s = state, id = root.setInterval(function () { s = action(s); }, period); + return disposableCreate(function () { root.clearInterval(id); }); + }; + + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchError = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + }(Scheduler.prototype)); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** Gets a scheduler that schedules work immediately on the current thread. */ + var immediateScheduler = Scheduler.immediate = (function () { + function scheduleNow(state, action) { return action(this, state); } + return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline () { + while (queue.length > 0) { + var item = queue.dequeue(); + !item.isCancelled() && item.invoke(); + } + } + + function scheduleNow(state, action) { + var si = new ScheduledItem(this, state, action, this.now()); + + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + + var result = tryCatch(runTrampoline)(); + queue = null; + if (result === errorObj) { return thrower(result.e); } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); + currentScheduler.scheduleRequired = function () { return !queue; }; + + return currentScheduler; + }()); + + var scheduleMethod, clearMethod; + + var localTimer = (function () { + var localSetTimeout, localClearTimeout = noop; + if (!!root.setTimeout) { + localSetTimeout = root.setTimeout; + localClearTimeout = root.clearTimeout; + } else if (!!root.WScript) { + localSetTimeout = function (fn, time) { + root.WScript.Sleep(time); + fn(); + }; + } else { + throw new NotSupportedError(); + } + + return { + setTimeout: localSetTimeout, + clearTimeout: localClearTimeout + }; + }()); + var localSetTimeout = localTimer.setTimeout, + localClearTimeout = localTimer.clearTimeout; + + (function () { + + var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; + + clearMethod = function (handle) { + delete tasksByHandle[handle]; + }; + + function runTask(handle) { + if (currentlyRunning) { + localSetTimeout(function () { runTask(handle) }, 0); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunning = true; + var result = tryCatch(task)(); + clearMethod(handle); + currentlyRunning = false; + if (result === errorObj) { return thrower(result.e); } + } + } + } + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('', '*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout + if (isFunction(setImmediate)) { + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + setImmediate(function () { runTask(id); }); + + return id; + }; + } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + process.nextTick(function () { runTask(id); }); + + return id; + }; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + runTask(event.data.substring(MSG_PREFIX.length)); + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else if (root.attachEvent) { + root.attachEvent('onmessage', onGlobalPostMessage); + } else { + root.onmessage = onGlobalPostMessage; + } + + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + return id; + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(); + + channel.port1.onmessage = function (e) { runTask(e.data); }; + + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + channel.port2.postMessage(id); + return id; + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + var id = nextHandle++; + tasksByHandle[id] = action; + + scriptElement.onreadystatechange = function () { + runTask(id); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + return id; + }; + + } else { + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + localSetTimeout(function () { + runTask(id); + }, 0); + + return id; + }; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () { + + function scheduleNow(state, action) { + var scheduler = this, disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, dt = Scheduler.normalize(dueTime), disposable = new SingleAssignmentDisposable(); + if (dt === 0) { return scheduler.scheduleWithState(state, action); } + var id = localSetTimeout(function () { + !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + localClearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + var CatchScheduler = (function (__super__) { + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, __super__); + + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); + } + + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, value, exception, accept, acceptObservable, toString) { + this.kind = kind; + this.value = value; + this.exception = exception; + this._accept = accept; + this._acceptObservable = acceptObservable; + this.toString = toString; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var self = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithState(self, function (_, notification) { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + function _accept(onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString() { return 'OnNext(' + this.value + ')'; } + + return function (value) { + return new Notification('N', value, null, _accept, _acceptObservable, toString); + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (e) { + return new Notification('E', null, e, _accept, _acceptObservable, toString); + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + return new Notification('C', null, null, _accept, _acceptObservable, toString); + }; + }()); + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { return n.accept(observer); }; + }; + + /** + * Hides the identity of an observer. + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler, thisArg) { + return new AnonymousObserver(function (x) { + return handler.call(thisArg, notificationCreateOnNext(x)); + }, function (e) { + return handler.call(thisArg, notificationCreateOnError(e)); + }, function () { + return handler.call(thisArg, notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.prototype.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + Observer.prototype.makeSafe = function(disposable) { + return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { + inherits(AbstractObserver, __super__); + + /** + * Creates a new observer in a non-stopped state. + */ + function AbstractObserver() { + this.isStopped = false; + __super__.call(this); + } + + // Must be implemented by other observers + AbstractObserver.prototype.next = notImplemented; + AbstractObserver.prototype.error = notImplemented; + AbstractObserver.prototype.completed = notImplemented; + + /** + * Notifies the observer of a new element in the sequence. + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { this.next(value); } + }; + + /** + * Notifies the observer that an exception has occurred. + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { + inherits(AnonymousObserver, __super__); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + __super__.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (error) { + this._onError(error); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (__super__) { + inherits(CheckedObserver, __super__); + + function CheckedObserver(observer) { + __super__.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + var res = tryCatch(this._observer.onNext).call(this._observer, value); + this._state = 0; + res === errorObj && thrower(res.e); + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + var res = tryCatch(this._observer.onError).call(this._observer, err); + this._state = 2; + res === errorObj && thrower(res.e); + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + var res = tryCatch(this._observer.onCompleted).call(this._observer); + this._state = 2; + res === errorObj && thrower(res.e); + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { + inherits(ScheduledObserver, __super__); + + function ScheduledObserver(scheduler, observer) { + __super__.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { self.observer.onNext(value); }); + }; + + ScheduledObserver.prototype.error = function (e) { + var self = this; + this.queue.push(function () { self.observer.onError(e); }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { self.observer.onCompleted(); }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + __super__.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + var ObserveOnObserver = (function (__super__) { + inherits(ObserveOnObserver, __super__); + + function ObserveOnObserver(scheduler, observer, cancel) { + __super__.call(this, scheduler, observer); + this._cancel = cancel; + } + + ObserveOnObserver.prototype.next = function (value) { + __super__.prototype.next.call(this, value); + this.ensureActive(); + }; + + ObserveOnObserver.prototype.error = function (e) { + __super__.prototype.error.call(this, e); + this.ensureActive(); + }; + + ObserveOnObserver.prototype.completed = function () { + __super__.prototype.completed.call(this); + this.ensureActive(); + }; + + ObserveOnObserver.prototype.dispose = function () { + __super__.prototype.dispose.call(this); + this._cancel && this._cancel.dispose(); + this._cancel = null; + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + if (Rx.config.longStackSupport && hasStacks) { + try { + throw new Error(); + } catch (e) { + this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); + } + + var self = this; + this._subscribe = function (observer) { + var oldOnError = observer.onError.bind(observer); + + observer.onError = function (err) { + makeStackTraceLong(err, self); + oldOnError(err); + }; + + return subscribe.call(self, observer); + }; + } else { + this._subscribe = subscribe; + } + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + return this._subscribe(typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted)); + }; + + /** + * Subscribes to the next value in the sequence with an optional "this" argument. + * @param {Function} onNext The function to invoke on each element in the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribeOnNext = function (onNext, thisArg) { + return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); + }; + + /** + * Subscribes to an exceptional condition in the sequence with an optional "this" argument. + * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribeOnError = function (onError, thisArg) { + return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); + }; + + /** + * Subscribes to the next value in the sequence with an optional "this" argument. + * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { + return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); + }; + + return Observable; + })(); + + var ObservableBase = Rx.ObservableBase = (function (__super__) { + inherits(ObservableBase, __super__); + + function fixSubscriber(subscriber) { + return subscriber && isFunction(subscriber.dispose) ? subscriber : + isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; + } + + function setDisposable(s, state) { + var ado = state[0], self = state[1]; + var sub = tryCatch(self.subscribeCore).call(self, ado); + + if (sub === errorObj) { + if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } + } + ado.setDisposable(fixSubscriber(sub)); + } + + function subscribe(observer) { + var ado = new AutoDetachObserver(observer), state = [ado, this]; + + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.scheduleWithState(state, setDisposable); + } else { + setDisposable(null, state); + } + return ado; + } + + function ObservableBase() { + __super__.call(this, subscribe); + } + + ObservableBase.prototype.subscribeCore = notImplemented; + + return ObservableBase; + }(Observable)); + + var Enumerable = Rx.internals.Enumerable = function () { }; + + var ConcatEnumerableObservable = (function(__super__) { + inherits(ConcatEnumerableObservable, __super__); + function ConcatEnumerableObservable(sources) { + this.sources = sources; + __super__.call(this); + } + + ConcatEnumerableObservable.prototype.subscribeCore = function (o) { + var isDisposed, subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](), function (e, self) { + if (isDisposed) { return; } + var currentItem = tryCatch(e.next).call(e); + if (currentItem === errorObj) { return o.onError(currentItem.e); } + + if (currentItem.done) { + return o.onCompleted(); + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e))); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }; + + function InnerObserver(o, s, e) { + this.o = o; + this.s = s; + this.e = e; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.o.onNext(x); } }; + InnerObserver.prototype.onError = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.s(this.e); + } + }; + InnerObserver.prototype.dispose = function () { this.isStopped = true; }; + InnerObserver.prototype.fail = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + return true; + } + return false; + }; + + return ConcatEnumerableObservable; + }(ObservableBase)); + + Enumerable.prototype.concat = function () { + return new ConcatEnumerableObservable(this); + }; + + var CatchErrorObservable = (function(__super__) { + inherits(CatchErrorObservable, __super__); + function CatchErrorObservable(sources) { + this.sources = sources; + __super__.call(this); + } + + CatchErrorObservable.prototype.subscribeCore = function (o) { + var e = this.sources[$iterator$](); + + var isDisposed, subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { + if (isDisposed) { return; } + var currentItem = tryCatch(e.next).call(e); + if (currentItem === errorObj) { return o.onError(currentItem.e); } + + if (currentItem.done) { + return lastException !== null ? o.onError(lastException) : o.onCompleted(); + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + function(x) { o.onNext(x); }, + self, + function() { o.onCompleted(); })); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }; + + return CatchErrorObservable; + }(ObservableBase)); + + Enumerable.prototype.catchError = function () { + return new CatchErrorObservable(this); + }; + + Enumerable.prototype.catchErrorWhen = function (notificationHandler) { + var sources = this; + return new AnonymousObservable(function (o) { + var exceptions = new Subject(), + notifier = new Subject(), + handled = notificationHandler(exceptions), + notificationDisposable = handled.subscribe(notifier); + + var e = sources[$iterator$](); + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + var currentItem = tryCatch(e.next).call(e); + if (currentItem === errorObj) { return o.onError(currentItem.e); } + + if (currentItem.done) { + if (lastException) { + o.onError(lastException); + } else { + o.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var outer = new SingleAssignmentDisposable(); + var inner = new SingleAssignmentDisposable(); + subscription.setDisposable(new CompositeDisposable(inner, outer)); + outer.setDisposable(currentValue.subscribe( + function(x) { o.onNext(x); }, + function (exn) { + inner.setDisposable(notifier.subscribe(self, function(ex) { + o.onError(ex); + }, function() { + o.onCompleted(); + })); + + exceptions.onNext(exn); + }, + function() { o.onCompleted(); })); + }); + + return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var RepeatEnumerable = (function (__super__) { + inherits(RepeatEnumerable, __super__); + + function RepeatEnumerable(v, c) { + this.v = v; + this.c = c == null ? -1 : c; + } + RepeatEnumerable.prototype[$iterator$] = function () { + return new RepeatEnumerator(this); + }; + + function RepeatEnumerator(p) { + this.v = p.v; + this.l = p.c; + } + RepeatEnumerator.prototype.next = function () { + if (this.l === 0) { return doneEnumerator; } + if (this.l > 0) { this.l--; } + return { done: false, value: this.v }; + }; + + return RepeatEnumerable; + }(Enumerable)); + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + return new RepeatEnumerable(value, repeatCount); + }; + + var OfEnumerable = (function(__super__) { + inherits(OfEnumerable, __super__); + function OfEnumerable(s, fn, thisArg) { + this.s = s; + this.fn = fn ? bindCallback(fn, thisArg, 3) : null; + } + OfEnumerable.prototype[$iterator$] = function () { + return new OfEnumerator(this); + }; + + function OfEnumerator(p) { + this.i = -1; + this.s = p.s; + this.l = this.s.length; + this.fn = p.fn; + } + OfEnumerator.prototype.next = function () { + return ++this.i < this.l ? + { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } : + doneEnumerator; + }; + + return OfEnumerable; + }(Enumerable)); + + var enumerableOf = Enumerable.of = function (source, selector, thisArg) { + return new OfEnumerable(source, selector, thisArg); + }; + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }, source); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }, source); + }; + + var FromPromiseObservable = (function(__super__) { + inherits(FromPromiseObservable, __super__); + function FromPromiseObservable(p) { + this.p = p; + __super__.call(this); + } + + FromPromiseObservable.prototype.subscribeCore = function(o) { + this.p.then(function (data) { + o.onNext(data); + o.onCompleted(); + }, function (err) { o.onError(err); }); + return disposableEmpty; + }; + + return FromPromiseObservable; + }(ObservableBase)); + + /** + * 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 FromPromiseObservable(promise); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, reject, function () { + hasValue && resolve(value); + }); + }); + }; + + var ToArrayObservable = (function(__super__) { + inherits(ToArrayObservable, __super__); + function ToArrayObservable(source) { + this.source = source; + __super__.call(this); + } + + ToArrayObservable.prototype.subscribeCore = function(o) { + return this.source.subscribe(new InnerObserver(o)); + }; + + function InnerObserver(o) { + this.o = o; + this.a = []; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; + InnerObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + InnerObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.o.onNext(this.a); + this.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function () { this.isStopped = true; } + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + + return false; + }; + + return ToArrayObservable; + }(ObservableBase)); + + /** + * Creates an array from an observable sequence. + * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + return new ToArrayObservable(this); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe, parent) { + return new AnonymousObservable(subscribe, parent); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + var EmptyObservable = (function(__super__) { + inherits(EmptyObservable, __super__); + function EmptyObservable(scheduler) { + this.scheduler = scheduler; + __super__.call(this); + } + + EmptyObservable.prototype.subscribeCore = function (observer) { + var sink = new EmptySink(observer, this); + return sink.run(); + }; + + function EmptySink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + function scheduleItem(s, state) { + state.onCompleted(); + } + + EmptySink.prototype.run = function () { + return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); + }; + + return EmptyObservable; + }(ObservableBase)); + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new EmptyObservable(scheduler); + }; + + var FromObservable = (function(__super__) { + inherits(FromObservable, __super__); + function FromObservable(iterable, mapper, scheduler) { + this.iterable = iterable; + this.mapper = mapper; + this.scheduler = scheduler; + __super__.call(this); + } + + FromObservable.prototype.subscribeCore = function (observer) { + var sink = new FromSink(observer, this); + return sink.run(); + }; + + return FromObservable; + }(ObservableBase)); + + var FromSink = (function () { + function FromSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + FromSink.prototype.run = function () { + var list = Object(this.parent.iterable), + it = getIterable(list), + observer = this.observer, + mapper = this.parent.mapper; + + function loopRecursive(i, recurse) { + try { + var next = it.next(); + } catch (e) { + return observer.onError(e); + } + if (next.done) { + return observer.onCompleted(); + } + + var result = next.value; + + if (mapper) { + try { + result = mapper(result, i); + } catch (e) { + return observer.onError(e); + } + } + + observer.onNext(result); + recurse(i + 1); + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + return FromSink; + }()); + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function StringIterable(str) { + this._s = s; + } + + StringIterable.prototype[$iterator$] = function () { + return new StringIterator(this._s); + }; + + function StringIterator(str) { + this._s = s; + this._l = s.length; + this._i = 0; + } + + StringIterator.prototype[$iterator$] = function () { + return this; + }; + + StringIterator.prototype.next = function () { + return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; + }; + + function ArrayIterable(a) { + this._a = a; + } + + ArrayIterable.prototype[$iterator$] = function () { + return new ArrayIterator(this._a); + }; + + function ArrayIterator(a) { + this._a = a; + this._l = toLength(a); + this._i = 0; + } + + ArrayIterator.prototype[$iterator$] = function () { + return this; + }; + + ArrayIterator.prototype.next = function () { + return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; + }; + + function numberIsFinite(value) { + return typeof value === 'number' && root.isFinite(value); + } + + function isNan(n) { + return n !== n; + } + + function getIterable(o) { + var i = o[$iterator$], it; + if (!i && typeof o === 'string') { + it = new StringIterable(o); + return it[$iterator$](); + } + if (!i && o.length !== undefined) { + it = new ArrayIterable(o); + return it[$iterator$](); + } + if (!i) { throw new TypeError('Object is not iterable'); } + return o[$iterator$](); + } + + function sign(value) { + var number = +value; + if (number === 0) { return number; } + if (isNaN(number)) { return number; } + return number < 0 ? -1 : 1; + } + + function toLength(o) { + var len = +o.length; + if (isNaN(len)) { return 0; } + if (len === 0 || !numberIsFinite(len)) { return len; } + len = sign(len) * Math.floor(Math.abs(len)); + if (len <= 0) { return 0; } + if (len > maxSafeInteger) { return maxSafeInteger; } + return len; + } + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. + * @param {Function} [mapFn] Map function to call on every element of the array. + * @param {Any} [thisArg] The context to use calling the mapFn if provided. + * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { + if (iterable == null) { + throw new Error('iterable cannot be null.') + } + if (mapFn && !isFunction(mapFn)) { + throw new Error('mapFn when provided must be a function'); + } + if (mapFn) { + var mapper = bindCallback(mapFn, thisArg, 2); + } + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromObservable(iterable, mapper, scheduler); + } + + var FromArrayObservable = (function(__super__) { + inherits(FromArrayObservable, __super__); + function FromArrayObservable(args, scheduler) { + this.args = args; + this.scheduler = scheduler; + __super__.call(this); + } + + FromArrayObservable.prototype.subscribeCore = function (observer) { + var sink = new FromArraySink(observer, this); + return sink.run(); + }; + + return FromArrayObservable; + }(ObservableBase)); + + function FromArraySink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + FromArraySink.prototype.run = function () { + var observer = this.observer, args = this.parent.args, len = args.length; + function loopRecursive(i, recurse) { + if (i < len) { + observer.onNext(args[i]); + recurse(i + 1); + } else { + observer.onCompleted(); + } + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * @deprecated use Observable.from or Observable.of + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromArrayObservable(array, scheduler) + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (o) { + var first = true; + return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + hasResult && (result = resultSelector(state)); + } catch (e) { + return o.onError(e); + } + if (hasResult) { + o.onNext(result); + self(state); + } else { + o.onCompleted(); + } + }); + }); + }; + + function observableOf (scheduler, array) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromArrayObservable(array, scheduler); + } + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return new FromArrayObservable(args, currentThreadScheduler); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length, args = new Array(len - 1); + for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } + return new FromArrayObservable(args, scheduler); + }; + + /** + * Creates an Observable sequence from changes to an array using Array.observe. + * @param {Array} array An array to observe changes. + * @returns {Observable} An observable sequence containing changes to an array from Array.observe. + */ + Observable.ofArrayChanges = function(array) { + if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); } + if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') } + return new AnonymousObservable(function(observer) { + function observerFn(changes) { + for(var i = 0, len = changes.length; i < len; i++) { + observer.onNext(changes[i]); + } + } + + Array.observe(array, observerFn); + + return function () { + Array.unobserve(array, observerFn); + }; + }); + }; + + /** + * Creates an Observable sequence from changes to an object using Object.observe. + * @param {Object} obj An object to observe changes. + * @returns {Observable} An observable sequence containing changes to an object from Object.observe. + */ + Observable.ofObjectChanges = function(obj) { + if (obj == null) { throw new TypeError('object must not be null or undefined.'); } + if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Object.observe is not supported on your platform') } + return new AnonymousObservable(function(observer) { + function observerFn(changes) { + for(var i = 0, len = changes.length; i < len; i++) { + observer.onNext(changes[i]); + } + } + + Object.observe(obj, observerFn); + + return function () { + Object.unobserve(obj, observerFn); + }; + }); + }; + + var NeverObservable = (function(__super__) { + inherits(NeverObservable, __super__); + function NeverObservable() { + __super__.call(this); + } + + NeverObservable.prototype.subscribeCore = function (observer) { + return disposableEmpty; + }; + + return NeverObservable; + }(ObservableBase)); + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new NeverObservable(); + }; + + var PairsObservable = (function(__super__) { + inherits(PairsObservable, __super__); + function PairsObservable(obj, scheduler) { + this.obj = obj; + this.keys = Object.keys(obj); + this.scheduler = scheduler; + __super__.call(this); + } + + PairsObservable.prototype.subscribeCore = function (observer) { + var sink = new PairsSink(observer, this); + return sink.run(); + }; + + return PairsObservable; + }(ObservableBase)); + + function PairsSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + PairsSink.prototype.run = function () { + var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length; + function loopRecursive(i, recurse) { + if (i < len) { + var key = keys[i]; + observer.onNext([key, obj[key]]); + recurse(i + 1); + } else { + observer.onCompleted(); + } + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + /** + * Convert an object into an observable sequence of [key, value] pairs. + * @param {Object} obj The object to inspect. + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} An observable sequence of [key, value] pairs from the object. + */ + Observable.pairs = function (obj, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new PairsObservable(obj, scheduler); + }; + + var RangeObservable = (function(__super__) { + inherits(RangeObservable, __super__); + function RangeObservable(start, count, scheduler) { + this.start = start; + this.rangeCount = count; + this.scheduler = scheduler; + __super__.call(this); + } + + RangeObservable.prototype.subscribeCore = function (observer) { + var sink = new RangeSink(observer, this); + return sink.run(); + }; + + return RangeObservable; + }(ObservableBase)); + + var RangeSink = (function () { + function RangeSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + RangeSink.prototype.run = function () { + var start = this.parent.start, count = this.parent.rangeCount, observer = this.observer; + function loopRecursive(i, recurse) { + if (i < count) { + observer.onNext(start + i); + recurse(i + 1); + } else { + observer.onCompleted(); + } + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + return RangeSink; + }()); + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new RangeObservable(start, count, scheduler); + }; + + var RepeatObservable = (function(__super__) { + inherits(RepeatObservable, __super__); + function RepeatObservable(value, repeatCount, scheduler) { + this.value = value; + this.repeatCount = repeatCount == null ? -1 : repeatCount; + this.scheduler = scheduler; + __super__.call(this); + } + + RepeatObservable.prototype.subscribeCore = function (observer) { + var sink = new RepeatSink(observer, this); + return sink.run(); + }; + + return RepeatObservable; + }(ObservableBase)); + + function RepeatSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + RepeatSink.prototype.run = function () { + var observer = this.observer, value = this.parent.value; + function loopRecursive(i, recurse) { + if (i === -1 || i > 0) { + observer.onNext(value); + i > 0 && i--; + } + if (i === 0) { return observer.onCompleted(); } + recurse(i); + } + + return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new RepeatObservable(value, repeatCount, scheduler); + }; + + var JustObservable = (function(__super__) { + inherits(JustObservable, __super__); + function JustObservable(value, scheduler) { + this.value = value; + this.scheduler = scheduler; + __super__.call(this); + } + + JustObservable.prototype.subscribeCore = function (observer) { + var sink = new JustSink(observer, this); + return sink.run(); + }; + + function JustSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + function scheduleItem(s, state) { + var value = state[0], observer = state[1]; + observer.onNext(value); + observer.onCompleted(); + } + + JustSink.prototype.run = function () { + return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); + }; + + return JustObservable; + }(ObservableBase)); + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just' or browsers 0) { + parent.handleSubscribe(parent.q.shift()); + } else { + parent.activeCount--; + parent.done && parent.activeCount === 0 && parent.o.onCompleted(); + } + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + return true; + } + + return false; + }; + + return MergeObserver; + }()); + + + + + + /** + * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. + * Or merges two observable sequences into a single observable sequence. + * + * @example + * 1 - merged = sources.merge(1); + * 2 - merged = source.merge(otherSource); + * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.merge = function (maxConcurrentOrOther) { + return typeof maxConcurrentOrOther !== 'number' ? + observableMerge(this, maxConcurrentOrOther) : + new MergeObservable(this, maxConcurrentOrOther); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources = [], i, len = arguments.length; + if (!arguments[0]) { + scheduler = immediateScheduler; + for(i = 1; i < len; i++) { sources.push(arguments[i]); } + } else if (isScheduler(arguments[0])) { + scheduler = arguments[0]; + for(i = 1; i < len; i++) { sources.push(arguments[i]); } + } else { + scheduler = immediateScheduler; + for(i = 0; i < len; i++) { sources.push(arguments[i]); } + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableOf(scheduler, sources).mergeAll(); + }; + + var MergeAllObservable = (function (__super__) { + inherits(MergeAllObservable, __super__); + + function MergeAllObservable(source) { + this.source = source; + __super__.call(this); + } + + MergeAllObservable.prototype.subscribeCore = function (observer) { + var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); + g.add(m); + m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); + return g; + }; + + function MergeAllObserver(o, g) { + this.o = o; + this.g = g; + this.isStopped = false; + this.done = false; + } + MergeAllObserver.prototype.onNext = function(innerSource) { + if(this.isStopped) { return; } + var sad = new SingleAssignmentDisposable(); + this.g.add(sad); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); + }; + MergeAllObserver.prototype.onError = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + MergeAllObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + this.isStopped = true; + this.done = true; + this.g.length === 1 && this.o.onCompleted(); + } + }; + MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; + MergeAllObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + + return false; + }; + + function InnerObserver(parent, g, sad) { + this.parent = parent; + this.g = g; + this.sad = sad; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; + InnerObserver.prototype.onError = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + } + }; + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + var parent = this.parent; + this.isStopped = true; + parent.g.remove(this.sad); + parent.done && parent.g.length === 1 && parent.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + return true; + } + + return false; + }; + + return MergeAllObservable; + }(ObservableBase)); + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeAll = observableProto.mergeObservable = function () { + return new MergeAllObservable(this); + }; + + var CompositeError = Rx.CompositeError = function(errors) { + this.name = "NotImplementedError"; + this.innerErrors = errors; + this.message = 'This contains multiple errors. Check the innerErrors'; + Error.call(this); + } + CompositeError.prototype = Error.prototype; + + /** + * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to + * receive all successfully emitted items from all of the source Observables without being interrupted by + * an error notification from one of them. + * + * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an + * error via the Observer's onError, mergeDelayError will refrain from propagating that + * error notification until all of the merged Observables have finished emitting items. + * @param {Array | Arguments} args Arguments or an array to merge. + * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable + */ + Observable.mergeDelayError = function() { + var args; + if (Array.isArray(arguments[0])) { + args = arguments[0]; + } else { + var len = arguments.length; + args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + } + var source = observableOf(null, args); + + return new AnonymousObservable(function (o) { + var group = new CompositeDisposable(), + m = new SingleAssignmentDisposable(), + isStopped = false, + errors = []; + + function setCompletion() { + if (errors.length === 0) { + o.onCompleted(); + } else if (errors.length === 1) { + o.onError(errors[0]); + } else { + o.onError(new CompositeError(errors)); + } + } + + group.add(m); + + m.setDisposable(source.subscribe( + function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check for promises support + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { o.onNext(x); }, + function (e) { + errors.push(e); + group.remove(innerSubscription); + isStopped && group.length === 1 && setCompletion(); + }, + function () { + group.remove(innerSubscription); + isStopped && group.length === 1 && setCompletion(); + })); + }, + function (e) { + errors.push(e); + isStopped = true; + group.length === 1 && setCompletion(); + }, + function () { + isStopped = true; + group.length === 1 && setCompletion(); + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { throw new Error('Second observable is required'); } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = []; + if (Array.isArray(arguments[0])) { + sources = arguments[0]; + } else { + for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } + } + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (o) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && o.onNext(left); + }, function (e) { o.onError(e); }, function () { + isOpen && o.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, function (e) { o.onError(e); }, function () { + rightSubscription.dispose(); + })); + + return disposables; + }, source); + }; + + var SwitchObservable = (function(__super__) { + inherits(SwitchObservable, __super__); + function SwitchObservable(source) { + this.source = source; + __super__.call(this); + } + + SwitchObservable.prototype.subscribeCore = function (o) { + var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner)); + return new CompositeDisposable(s, inner); + }; + + function SwitchObserver(o, inner) { + this.o = o; + this.inner = inner; + this.stopped = false; + this.latest = 0; + this.hasLatest = false; + this.isStopped = false; + } + SwitchObserver.prototype.onNext = function (innerSource) { + if (this.isStopped) { return; } + var d = new SingleAssignmentDisposable(), id = ++this.latest; + this.hasLatest = true; + this.inner.setDisposable(d); + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + d.setDisposable(innerSource.subscribe(new InnerObserver(this, id))); + }; + SwitchObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + SwitchObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.stopped = true; + !this.hasLatest && this.o.onCompleted(); + } + }; + SwitchObserver.prototype.dispose = function () { this.isStopped = true; }; + SwitchObserver.prototype.fail = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + function InnerObserver(parent, id) { + this.parent = parent; + this.id = id; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + this.parent.latest === this.id && this.parent.o.onNext(x); + }; + InnerObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.parent.latest === this.id && this.parent.o.onError(e); + } + }; + InnerObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + if (this.parent.latest === this.id) { + this.parent.hasLatest = false; + this.parent.isStopped && this.parent.o.onCompleted(); + } + } + }; + InnerObserver.prototype.dispose = function () { this.isStopped = true; } + InnerObserver.prototype.fail = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + return true; + } + return false; + }; + + return SwitchObservable; + }(ObservableBase)); + + /** + * 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 () { + return new SwitchObservable(this); + }; + + var TakeUntilObservable = (function(__super__) { + inherits(TakeUntilObservable, __super__); + + function TakeUntilObservable(source, other) { + this.source = source; + this.other = isPromise(other) ? observableFromPromise(other) : other; + __super__.call(this); + } + + TakeUntilObservable.prototype.subscribeCore = function(o) { + return new CompositeDisposable( + this.source.subscribe(o), + this.other.subscribe(new InnerObserver(o)) + ); + }; + + function InnerObserver(o) { + this.o = o; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + this.o.onCompleted(); + }; + InnerObserver.prototype.onError = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function () { + !this.isStopped && (this.isStopped = true); + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + return TakeUntilObservable; + }(ObservableBase)); + + /** + * 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) { + return new TakeUntilObservable(this, other); + }; + + function falseFactory() { return false; } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.withLatestFrom = function () { + var len = arguments.length, args = new Array(len) + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + var resultSelector = args.pop(), source = this; + Array.isArray(args[0]) && (args = args[0]); + + return new AnonymousObservable(function (observer) { + var n = args.length, + hasValue = arrayInitialize(n, falseFactory), + hasValueAll = false, + values = new Array(n); + + var subscriptions = new Array(n + 1); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var other = args[i], sad = new SingleAssignmentDisposable(); + isPromise(other) && (other = observableFromPromise(other)); + sad.setDisposable(other.subscribe(function (x) { + values[i] = x; + hasValue[i] = true; + hasValueAll = hasValue.every(identity); + }, function (e) { observer.onError(e); }, noop)); + subscriptions[i] = sad; + }(idx)); + } + + var sad = new SingleAssignmentDisposable(); + sad.setDisposable(source.subscribe(function (x) { + var allValues = [x].concat(values); + if (!hasValueAll) { return; } + var res = tryCatch(resultSelector).apply(null, allValues); + if (res === errorObj) { return observer.onError(res.e); } + observer.onNext(res); + }, function (e) { observer.onError(e); }, function () { + observer.onCompleted(); + })); + subscriptions[n] = sad; + + return new CompositeDisposable(subscriptions); + }, this); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (o) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], res = tryCatch(resultSelector)(left, right); + if (res === errorObj) { return o.onError(res.e); } + o.onNext(res); + } else { + o.onCompleted(); + } + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, first); + } + + function falseFactory() { return false; } + function emptyArrayFactory() { return []; } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. + * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + + var parent = this, resultSelector = args.pop(); + args.unshift(parent); + return new AnonymousObservable(function (o) { + var n = args.length, + queues = arrayInitialize(n, emptyArrayFactory), + isDone = arrayInitialize(n, falseFactory); + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = args[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + if (queues.every(function (x) { return x.length > 0; })) { + var queuedValues = queues.map(function (x) { return x.shift(); }), + res = tryCatch(resultSelector).apply(parent, queuedValues); + if (res === errorObj) { return o.onError(res.e); } + o.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + o.onCompleted(); + } + }, function (e) { o.onError(e); }, function () { + isDone[i] = true; + isDone.every(identity) && o.onCompleted(); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }, parent); + }; + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + var first = args.shift(); + return first.zip.apply(first, args); + }; + + function falseFactory() { return false; } + function arrayFactory() { return []; } + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources; + if (Array.isArray(arguments[0])) { + sources = arguments[0]; + } else { + var len = arguments.length; + sources = new Array(len); + for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } + } + return new AnonymousObservable(function (o) { + var n = sources.length, + queues = arrayInitialize(n, arrayFactory), + isDone = arrayInitialize(n, falseFactory); + + 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); + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + o.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + return o.onCompleted(); + } + }, function (e) { o.onError(e); }, function () { + isDone[i] = true; + isDone.every(identity) && o.onCompleted(); + })); + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (o) { return source.subscribe(o); }, source); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (o) { + return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); + }, this); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (o) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var key = value; + if (keySelector) { + key = tryCatch(keySelector)(value); + if (key === errorObj) { return o.onError(key.e); } + } + if (hasCurrentKey) { + var comparerEquals = tryCatch(comparer)(currentKey, key); + if (comparerEquals === errorObj) { return o.onError(comparerEquals.e); } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + o.onNext(value); + } + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, this); + }; + + var TapObservable = (function(__super__) { + inherits(TapObservable,__super__); + function TapObservable(source, observerOrOnNext, onError, onCompleted) { + this.source = source; + this.t = !observerOrOnNext || isFunction(observerOrOnNext) ? + observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : + observerOrOnNext; + __super__.call(this); + } + + TapObservable.prototype.subscribeCore = function(o) { + return this.source.subscribe(new InnerObserver(o, this.t)); + }; + + function InnerObserver(o, t) { + this.o = o; + this.t = t; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function(x) { + if (this.isStopped) { return; } + var res = tryCatch(this.t.onNext).call(this.t, x); + if (res === errorObj) { this.o.onError(res.e); } + this.o.onNext(x); + }; + InnerObserver.prototype.onError = function(err) { + if (!this.isStopped) { + this.isStopped = true; + var res = tryCatch(this.t.onError).call(this.t, err); + if (res === errorObj) { return this.o.onError(res.e); } + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function() { + if (!this.isStopped) { + this.isStopped = true; + var res = tryCatch(this.t.onCompleted).call(this.t); + if (res === errorObj) { return this.o.onError(res.e); } + this.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + return TapObservable; + }(ObservableBase)); + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + return new TapObservable(this, observerOrOnNext, onError, onCompleted); + }; + + /** + * Invokes an action for each element in the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function} onNext Action to invoke for each element in the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { + return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); + }; + + /** + * Invokes an action upon exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { + return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); + }; + + /** + * Invokes an action upon graceful termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { + return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.ensure = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }, this); + }; + + /** + * @deprecated use #finally or #ensure instead. + */ + observableProto.finallyAction = function (action) { + //deprecate('finallyAction', 'finally or ensure'); + return this.ensure(action); + }; + + var IgnoreElementsObservable = (function(__super__) { + inherits(IgnoreElementsObservable, __super__); + + function IgnoreElementsObservable(source) { + this.source = source; + __super__.call(this); + } + + IgnoreElementsObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o)); + }; + + function InnerObserver(o) { + this.o = o; + this.isStopped = false; + } + InnerObserver.prototype.onNext = noop; + InnerObserver.prototype.onError = function (err) { + if(!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + this.isStopped = true; + this.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.observer.onError(e); + return true; + } + + return false; + }; + + return IgnoreElementsObservable; + }(ObservableBase)); + + /** + * 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 () { + return new IgnoreElementsObservable(this); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }, source); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * Note if you encounter an error and want it to retry once, then you must use .retry(2); + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(2); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchError(); + }; + + /** + * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. + * if the notifier completes, the observable sequence completes. + * + * @example + * var timer = Observable.timer(500); + * var source = observable.retryWhen(timer); + * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retryWhen = function (notifier) { + return enumerableRepeat(this).catchErrorWhen(notifier); + }; + var ScanObservable = (function(__super__) { + inherits(ScanObservable, __super__); + function ScanObservable(source, accumulator, hasSeed, seed) { + this.source = source; + this.accumulator = accumulator; + this.hasSeed = hasSeed; + this.seed = seed; + __super__.call(this); + } + + ScanObservable.prototype.subscribeCore = function(observer) { + return this.source.subscribe(new ScanObserver(observer,this)); + }; + + return ScanObservable; + }(ObservableBase)); + + function ScanObserver(observer, parent) { + this.observer = observer; + this.accumulator = parent.accumulator; + this.hasSeed = parent.hasSeed; + this.seed = parent.seed; + this.hasAccumulation = false; + this.accumulation = null; + this.hasValue = false; + this.isStopped = false; + } + ScanObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + !this.hasValue && (this.hasValue = true); + try { + if (this.hasAccumulation) { + this.accumulation = this.accumulator(this.accumulation, x); + } else { + this.accumulation = this.hasSeed ? this.accumulator(this.seed, x) : x; + this.hasAccumulation = true; + } + } catch (e) { + return this.observer.onError(e); + } + this.observer.onNext(this.accumulation); + }; + ScanObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.observer.onError(e); + } + }; + ScanObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + !this.hasValue && this.hasSeed && this.observer.onNext(this.seed); + this.observer.onCompleted(); + } + }; + ScanObserver.prototype.dispose = function() { this.isStopped = true; }; + ScanObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.observer.onError(e); + return true; + } + return false; + }; + + /** + * 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. + * @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 ScanObservable(this, accumulator, hasSeed, seed); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + if (count < 0) { throw new ArgumentOutOfRangeError(); } + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && o.onNext(q.shift()); + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, source); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * @example + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * @param {Arguments} args The specified values to prepend to the observable sequence + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && isScheduler(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } + return enumerableOf([observableFromArray(args, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence. + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count) { + if (count < 0) { throw new ArgumentOutOfRangeError(); } + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, function (e) { o.onError(e); }, function () { + while (q.length > 0) { o.onNext(q.shift()); } + o.onCompleted(); + }); + }, source); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, function (e) { o.onError(e); }, function () { + o.onNext(q); + o.onCompleted(); + }); + }, source); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + +count || (count = 0); + Math.abs(count) === Infinity && (count = 0); + if (count <= 0) { throw new ArgumentOutOfRangeError(); } + skip == null && (skip = count); + +skip || (skip = 0); + Math.abs(skip) === Infinity && (skip = 0); + + if (skip <= 0) { throw new ArgumentOutOfRangeError(); } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = []; + + function createWindow () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + + createWindow(); + + m.setDisposable(source.subscribe( + function (x) { + for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } + var c = n - count + 1; + c >= 0 && c % skip === 0 && q.shift().onCompleted(); + ++n % skip === 0 && createWindow(); + }, + function (e) { + while (q.length > 0) { q.shift().onError(e); } + observer.onError(e); + }, + function () { + while (q.length > 0) { q.shift().onCompleted(); } + observer.onCompleted(); + } + )); + return refCountDisposable; + }, source); + }; + + function concatMap(source, selector, thisArg) { + var selectorFunc = bindCallback(selector, thisArg, 3); + return source.map(function (x, i) { + var result = selectorFunc(x, i, source); + isPromise(result) && (result = observableFromPromise(result)); + (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); + return result; + }).concatAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); + * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { + if (isFunction(selector) && isFunction(resultSelector)) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i); + isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); + (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); + + return selectorResult.map(function (y, i2) { + return resultSelector(x, y, i, i2); + }); + }); + } + return isFunction(selector) ? + concatMap(this, selector, thisArg) : + concatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { + var source = this, + onNextFunc = bindCallback(onNext, thisArg, 2), + onErrorFunc = bindCallback(onError, thisArg, 1), + onCompletedFunc = bindCallback(onCompleted, thisArg, 0); + return new AnonymousObservable(function (observer) { + var index = 0; + return source.subscribe( + function (x) { + var result; + try { + result = onNextFunc(x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onErrorFunc(err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompletedFunc(); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }, this).concatAll(); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + defaultValue === undefined && (defaultValue = null); + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, + function (e) { observer.onError(e); }, + function () { + !found && observer.onNext(defaultValue); + observer.onCompleted(); + }); + }, source); + }; + + // Swap out for Array.findIndex + function arrayIndexOfComparer(array, item, comparer) { + for (var i = 0, len = array.length; i < len; i++) { + if (comparer(array[i], item)) { return i; } + } + return -1; + } + + function HashSet(comparer) { + this.comparer = comparer; + this.set = []; + } + HashSet.prototype.push = function(value) { + var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; + retValue && this.set.push(value); + return retValue; + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [comparer] Used to compare items in the collection. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (o) { + var hashSet = new HashSet(comparer); + return source.subscribe(function (x) { + var key = x; + + if (keySelector) { + try { + key = keySelector(x); + } catch (e) { + o.onError(e); + return; + } + } + hashSet.push(key) && o.onNext(x); + }, + function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, this); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [comparer] Used to determine whether the objects are equal. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, comparer) { + return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { + var source = this; + elementSelector || (elementSelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + function handleError(e) { return function (item) { item.onError(e); }; } + var map = new Dictionary(0, comparer), + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + + groupDisposable.add(source.subscribe(function (x) { + var key; + try { + key = keySelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + var fireNewMapEntry = false, + writer = map.tryGetValue(key); + if (!writer) { + writer = new Subject(); + map.set(key, writer); + fireNewMapEntry = true; + } + + if (fireNewMapEntry) { + var group = new GroupedObservable(key, writer, refCountDisposable), + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + observer.onNext(group); + + var md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + + var expire = function () { + map.remove(key) && writer.onCompleted(); + groupDisposable.remove(md); + }; + + md.setDisposable(duration.take(1).subscribe( + noop, + function (exn) { + map.getValues().forEach(handleError(exn)); + observer.onError(exn); + }, + expire) + ); + } + + var element; + try { + element = elementSelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + writer.onNext(element); + }, function (ex) { + map.getValues().forEach(handleError(ex)); + observer.onError(ex); + }, function () { + map.getValues().forEach(function (item) { item.onCompleted(); }); + observer.onCompleted(); + })); + + return refCountDisposable; + }, source); + }; + + var MapObservable = (function (__super__) { + inherits(MapObservable, __super__); + + function MapObservable(source, selector, thisArg) { + this.source = source; + this.selector = bindCallback(selector, thisArg, 3); + __super__.call(this); + } + + function innerMap(selector, self) { + return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); } + } + + MapObservable.prototype.internalMap = function (selector, thisArg) { + return new MapObservable(this.source, innerMap(selector, this), thisArg); + }; + + MapObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o, this.selector, this)); + }; + + function InnerObserver(o, selector, source) { + this.o = o; + this.selector = selector; + this.source = source; + this.i = 0; + this.isStopped = false; + } + + InnerObserver.prototype.onNext = function(x) { + if (this.isStopped) { return; } + var result = tryCatch(this.selector)(x, this.i++, this.source); + if (result === errorObj) { + return this.o.onError(result.e); + } + this.o.onNext(result); + }; + InnerObserver.prototype.onError = function (e) { + if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } + }; + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + + return false; + }; + + return MapObservable; + + }(ObservableBase)); + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.map = observableProto.select = function (selector, thisArg) { + var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; + return this instanceof MapObservable ? + this.internalMap(selectorFn, thisArg) : + new MapObservable(this, selectorFn, thisArg); + }; + + /** + * Retrieves the value of a specified nested property from all elements in + * the Observable sequence. + * @param {Arguments} arguments The nested properties to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function () { + var args = arguments, len = arguments.length; + if (len === 0) { throw new Error('List of properties cannot be empty.'); } + return this.map(function (x) { + var currentProp = x; + for (var i = 0; i < len; i++) { + var p = currentProp[args[i]]; + if (typeof p !== 'undefined') { + currentProp = p; + } else { + return undefined; + } + } + return currentProp; + }); + }; + + function flatMap(source, selector, thisArg) { + var selectorFunc = bindCallback(selector, thisArg, 3); + return source.map(function (x, i) { + var result = selectorFunc(x, i, source); + isPromise(result) && (result = observableFromPromise(result)); + (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); + return result; + }).mergeAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { + if (isFunction(selector) && isFunction(resultSelector)) { + return this.flatMap(function (x, i) { + var selectorResult = selector(x, i); + isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); + (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); + + return selectorResult.map(function (y, i2) { + return resultSelector(x, y, i, i2); + }); + }, thisArg); + } + return isFunction(selector) ? + flatMap(this, selector, thisArg) : + flatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }, source).mergeAll(); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + var SkipObservable = (function(__super__) { + inherits(SkipObservable, __super__); + function SkipObservable(source, count) { + this.source = source; + this.skipCount = count; + __super__.call(this); + } + + SkipObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o, this.skipCount)); + }; + + function InnerObserver(o, c) { + this.c = c; + this.r = c; + this.o = o; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + if (this.r <= 0) { + this.o.onNext(x); + } else { + this.r--; + } + }; + InnerObserver.prototype.onError = function(e) { + if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } + }; + InnerObserver.prototype.onCompleted = function() { + if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function(e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + return SkipObservable; + }(ObservableBase)); + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { throw new ArgumentOutOfRangeError(); } + return new SkipObservable(this, count); + }; + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this, + callback = bindCallback(predicate, thisArg, 3); + return new AnonymousObservable(function (o) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !callback(x, i++, source); + } catch (e) { + o.onError(e); + return; + } + } + running && o.onNext(x); + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, source); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0; }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + this.hasError = true; + this.error = error; + + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + this.value = value; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onNext(value); + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (__super__) { + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function createRemovableDisposable(subject, observer) { + return disposableCreate(function () { + observer.dispose(); + !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); + }); + } + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = createRemovableDisposable(this, so); + checkDisposed(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + so.onError(this.error); + } else if (this.isStopped) { + so.onCompleted(); + } + + so.ensureActive(); + return subscription; + } + + inherits(ReplaySubject, __super__); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; + this.windowSize = windowSize == null ? maxSafeInteger : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + __super__.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer.prototype, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onNext(value); + observer.ensureActive(); + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers.length = 0; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { + inherits(ConnectableObservable, __super__); + + function ConnectableObservable(source, subject) { + var hasSubscription = false, + subscription, + sourceObservable = source.asObservable(); + + this.connect = function () { + if (!hasSubscription) { + hasSubscription = true; + subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { + hasSubscription = false; + })); + } + return subscription; + }; + + __super__.call(this, function (o) { return subject.subscribe(o); }); + } + + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect = ++count === 1, + subscription = source.subscribe(observer); + shouldConnect && (connectableSubscription = source.connect()); + return function () { + subscription.dispose(); + --count === 0 && connectableSubscription.dispose(); + }; + }); + }; + + return ConnectableObservable; + }(Observable)); + + /** + * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence + * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`) + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source. + */ + observableProto.singleInstance = function() { + var source = this, hasObservable = false, observable; + + function getObservable() { + if (!hasObservable) { + hasObservable = true; + observable = source.finally(function() { hasObservable = false; }).publish().refCount(); + } + return observable; + }; + + return new AnonymousObservable(function(o) { + return getObservable().subscribe(o); + }); + }; + + var Dictionary = (function () { + + var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], + noSuchkey = "no such key", + duplicatekey = "duplicate key"; + + function isPrime(candidate) { + if ((candidate & 1) === 0) { return candidate === 2; } + var num1 = Math.sqrt(candidate), + num2 = 3; + while (num2 <= num1) { + if (candidate % num2 === 0) { return false; } + num2 += 2; + } + return true; + } + + function getPrime(min) { + var index, num, candidate; + for (index = 0; index < primes.length; ++index) { + num = primes[index]; + if (num >= min) { return num; } + } + candidate = min | 1; + while (candidate < primes[primes.length - 1]) { + if (isPrime(candidate)) { return candidate; } + candidate += 2; + } + return min; + } + + function stringHashFn(str) { + var hash = 757602046; + if (!str.length) { return hash; } + for (var i = 0, len = str.length; i < len; i++) { + var character = str.charCodeAt(i); + hash = ((hash << 5) - hash) + character; + hash = hash & hash; + } + return hash; + } + + function numberHashFn(key) { + var c2 = 0x27d4eb2d; + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + + var getHashCode = (function () { + var uniqueIdCounter = 0; + + return function (obj) { + if (obj == null) { throw new Error(noSuchkey); } + + // Check for built-ins before tacking on our own for any object + if (typeof obj === 'string') { return stringHashFn(obj); } + if (typeof obj === 'number') { return numberHashFn(obj); } + if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } + if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } + if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } + if (typeof obj.valueOf === 'function') { + // Hack check for valueOf + var valueOf = obj.valueOf(); + if (typeof valueOf === 'number') { return numberHashFn(valueOf); } + if (typeof valueOf === 'string') { return stringHashFn(valueOf); } + } + if (obj.hashCode) { return obj.hashCode(); } + + var id = 17 * uniqueIdCounter++; + obj.hashCode = function () { return id; }; + return id; + }; + }()); + + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } + + function Dictionary(capacity, comparer) { + if (capacity < 0) { throw new ArgumentOutOfRangeError(); } + if (capacity > 0) { this._initialize(capacity); } + + this.comparer = comparer || defaultComparer; + this.freeCount = 0; + this.size = 0; + this.freeList = -1; + } + + var dictionaryProto = Dictionary.prototype; + + dictionaryProto._initialize = function (capacity) { + var prime = getPrime(capacity), i; + this.buckets = new Array(prime); + this.entries = new Array(prime); + for (i = 0; i < prime; i++) { + this.buckets[i] = -1; + this.entries[i] = newEntry(); + } + this.freeList = -1; + }; + + dictionaryProto.add = function (key, value) { + this._insert(key, value, true); + }; + + dictionaryProto._insert = function (key, value, add) { + if (!this.buckets) { this._initialize(0); } + var index3, + num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length; + for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { + if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { + if (add) { throw new Error(duplicatekey); } + this.entries[index2].value = value; + return; + } + } + if (this.freeCount > 0) { + index3 = this.freeList; + this.freeList = this.entries[index3].next; + --this.freeCount; + } else { + if (this.size === this.entries.length) { + this._resize(); + index1 = num % this.buckets.length; + } + index3 = this.size; + ++this.size; + } + this.entries[index3].hashCode = num; + this.entries[index3].next = this.buckets[index1]; + this.entries[index3].key = key; + this.entries[index3].value = value; + this.buckets[index1] = index3; + }; + + dictionaryProto._resize = function () { + var prime = getPrime(this.size * 2), + numArray = new Array(prime); + for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } + var entryArray = new Array(prime); + for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } + for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } + for (var index1 = 0; index1 < this.size; ++index1) { + var index2 = entryArray[index1].hashCode % prime; + entryArray[index1].next = numArray[index2]; + numArray[index2] = index1; + } + this.buckets = numArray; + this.entries = entryArray; + }; + + dictionaryProto.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length, + index2 = -1; + for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { + if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { + if (index2 < 0) { + this.buckets[index1] = this.entries[index3].next; + } else { + this.entries[index2].next = this.entries[index3].next; + } + this.entries[index3].hashCode = -1; + this.entries[index3].next = this.freeList; + this.entries[index3].key = null; + this.entries[index3].value = null; + this.freeList = index3; + ++this.freeCount; + return true; + } else { + index2 = index3; + } + } + } + return false; + }; + + dictionaryProto.clear = function () { + var index, len; + if (this.size <= 0) { return; } + for (index = 0, len = this.buckets.length; index < len; ++index) { + this.buckets[index] = -1; + } + for (index = 0; index < this.size; ++index) { + this.entries[index] = newEntry(); + } + this.freeList = -1; + this.size = 0; + }; + + dictionaryProto._findEntry = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { + if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { + return index; + } + } + } + return -1; + }; + + dictionaryProto.count = function () { + return this.size - this.freeCount; + }; + + dictionaryProto.tryGetValue = function (key) { + var entry = this._findEntry(key); + return entry >= 0 ? + this.entries[entry].value : + undefined; + }; + + dictionaryProto.getValues = function () { + var index = 0, results = []; + if (this.entries) { + for (var index1 = 0; index1 < this.size; index1++) { + if (this.entries[index1].hashCode >= 0) { + results[index++] = this.entries[index1].value; + } + } + } + return results; + }; + + dictionaryProto.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { return this.entries[entry].value; } + throw new Error(noSuchkey); + }; + + dictionaryProto.set = function (key, value) { + this._insert(key, value, false); + }; + + dictionaryProto.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + return Dictionary; + }()); + + /** + * Correlates the elements of two sequences based on overlapping durations. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var leftDone = false, rightDone = false; + var leftId = 0, rightId = 0; + var leftMap = new Dictionary(), rightMap = new Dictionary(); + + group.add(left.subscribe( + function (value) { + var id = leftId++; + var md = new SingleAssignmentDisposable(); + + leftMap.add(id, value); + group.add(md); + + var expire = function () { + leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + rightMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(value, v); + } catch (exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + leftDone = true; + (rightDone || leftMap.count() === 0) && observer.onCompleted(); + }) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + var md = new SingleAssignmentDisposable(); + + rightMap.add(id, value); + group.add(md); + + var expire = function () { + rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + leftMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(v, value); + } catch (exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + rightDone = true; + (leftDone || rightMap.count() === 0) && observer.onCompleted(); + }) + ); + return group; + }, left); + }; + + /** + * Correlates the elements of two sequences based on overlapping durations, and groups the results. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(), rightMap = new Dictionary(); + var leftId = 0, rightId = 0; + + function handleError(e) { return function (v) { v.onError(e); }; }; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftId++; + leftMap.add(id, s); + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + observer.onNext(result); + + rightMap.getValues().forEach(function (v) { s.onNext(v); }); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + leftMap.remove(id) && s.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + observer.onCompleted.bind(observer)) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + rightMap.add(id, value); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + rightMap.remove(id); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + + leftMap.getValues().forEach(function (v) { v.onNext(value); }); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }) + ); + + return r; + }, left); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers. + * + * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { + return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows. + * + * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { + if (arguments.length === 1 && typeof arguments[0] !== 'function') { + return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); + } + return typeof windowOpeningsOrClosingSelector === 'function' ? + observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : + observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); + }; + + function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { + return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { + return win; + }); + } + + function observableWindowWithBoundaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var win = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); + + observer.onNext(addRef(win, r)); + + d.add(source.subscribe(function (x) { + win.onNext(x); + }, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + observer.onCompleted(); + })); + + isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); + + d.add(windowBoundaries.subscribe(function (w) { + win.onCompleted(); + win = new Subject(); + observer.onNext(addRef(win, r)); + }, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + observer.onCompleted(); + })); + + return r; + }, source); + } + + function observableWindowWithClosingSelector(windowClosingSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SerialDisposable(), + d = new CompositeDisposable(m), + r = new RefCountDisposable(d), + win = new Subject(); + observer.onNext(addRef(win, r)); + d.add(source.subscribe(function (x) { + win.onNext(x); + }, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + observer.onCompleted(); + })); + + function createWindowClose () { + var windowClose; + try { + windowClose = windowClosingSelector(); + } catch (e) { + observer.onError(e); + return; + } + + isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); + + var m1 = new SingleAssignmentDisposable(); + m.setDisposable(m1); + m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + win = new Subject(); + observer.onNext(addRef(win, r)); + createWindowClose(); + })); + } + + createWindowClose(); + return r; + }, source); + } + + /** + * 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)); + }, source); + }; + + /** + * 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) { + return [ + this.filter(predicate, thisArg), + this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + var WhileEnumerable = (function(__super__) { + inherits(WhileEnumerable, __super__); + function WhileEnumerable(c, s) { + this.c = c; + this.s = s; + } + WhileEnumerable.prototype[$iterator$] = function () { + var self = this; + return { + next: function () { + return self.c() ? + { done: false, value: self.s } : + { done: true, value: void 0 }; + } + }; + }; + return WhileEnumerable; + }(Enumerable)); + + function enumerableWhile(condition, source) { + return new WhileEnumerable(condition, source); + } + + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.letBind = observableProto['let'] = function (func) { + return func(this); + }; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) { + isOwner = !isAcquired; + isAcquired = true; + } + if (isOwner) { + m.setDisposable(scheduler.scheduleRecursive(function (self) { + var work; + if (q.length > 0) { + work = q.shift(); + } else { + isAcquired = false; + return; + } + var m1 = new SingleAssignmentDisposable(); + d.add(m1); + m1.setDisposable(work.subscribe(function (x) { + observer.onNext(x); + var result = null; + try { + result = selector(x); + } catch (e) { + observer.onError(e); + } + q.push(result); + activeCount++; + ensureActive(); + }, observer.onError.bind(observer), function () { + d.remove(m1); + activeCount--; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + self(); + })); + } + }; + + q.push(source); + activeCount++; + ensureActive(); + return d; + }, this); + }; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); + * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. + */ + Observable.forkJoin = function () { + var allSources = []; + if (Array.isArray(arguments[0])) { + allSources = arguments[0]; + } else { + for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } + } + return new AnonymousObservable(function (subscriber) { + var count = allSources.length; + if (count === 0) { + subscriber.onCompleted(); + return disposableEmpty; + } + var group = new CompositeDisposable(), + finished = false, + hasResults = new Array(count), + hasCompleted = new Array(count), + results = new Array(count); + + for (var idx = 0; idx < count; idx++) { + (function (i) { + var source = allSources[i]; + isPromise(source) && (source = observableFromPromise(source)); + group.add( + source.subscribe( + function (value) { + if (!finished) { + hasResults[i] = true; + results[i] = value; + } + }, + function (e) { + finished = true; + subscriber.onError(e); + group.dispose(); + }, + function () { + if (!finished) { + if (!hasResults[i]) { + subscriber.onCompleted(); + return; + } + hasCompleted[i] = true; + for (var ix = 0; ix < count; ix++) { + if (!hasCompleted[ix]) { return; } + } + finished = true; + subscriber.onNext(results); + subscriber.onCompleted(); + } + })); + })(idx); + } + + return group; + }); + }; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param {Observable} second Second observable sequence. + * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + observableProto.forkJoin = function (second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + isPromise(second) && (second = observableFromPromise(second)); + + leftSubscription.setDisposable( + first.subscribe(function (left) { + hasLeft = true; + lastLeft = left; + }, function (err) { + rightSubscription.dispose(); + observer.onError(err); + }, function () { + leftStopped = true; + if (rightStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + rightSubscription.setDisposable( + second.subscribe(function (right) { + hasRight = true; + lastRight = right; + }, function (err) { + leftSubscription.dispose(); + observer.onError(err); + }, function () { + rightStopped = true; + if (leftStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }, first); + }; + + /** + * Comonadic bind operator. + * @param {Function} selector A transform function to apply to each element. + * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns {Observable} An observable sequence which results from the comonadic bind operation. + */ + observableProto.manySelect = observableProto.extend = function (selector, scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + var source = this; + return observableDefer(function () { + var chain; + + return source + .map(function (x) { + var curr = new ChainObservable(x); + + chain && chain.onNext(x); + chain = curr; + + return curr; + }) + .tap( + noop, + function (e) { chain && chain.onError(e); }, + function () { chain && chain.onCompleted(); } + ) + .observeOn(scheduler) + .map(selector); + }, source); + }; + + var ChainObservable = (function (__super__) { + + function subscribe (observer) { + var self = this, g = new CompositeDisposable(); + g.add(currentThreadScheduler.schedule(function () { + observer.onNext(self.head); + g.add(self.tail.mergeAll().subscribe(observer)); + })); + + return g; + } + + inherits(ChainObservable, __super__); + + function ChainObservable(head) { + __super__.call(this, subscribe); + this.head = head; + this.tail = new AsyncSubject(); + } + + addProperties(ChainObservable.prototype, Observer, { + onCompleted: function () { + this.onNext(Observable.empty()); + }, + onError: function (e) { + this.onNext(Observable.throwError(e)); + }, + onNext: function (v) { + this.tail.onNext(v); + this.tail.onCompleted(); + } + }); + + return ChainObservable; + + }(Observable)); + + /** @private */ + var Map = root.Map || (function () { + + function Map() { + this._keys = []; + this._values = []; + } + + Map.prototype.get = function (key) { + var i = this._keys.indexOf(key); + return i !== -1 ? this._values[i] : undefined; + }; + + Map.prototype.set = function (key, value) { + var i = this._keys.indexOf(key); + i !== -1 && (this._values[i] = value); + this._values[this._keys.push(key) - 1] = value; + }; + + Map.prototype.forEach = function (callback, thisArg) { + for (var i = 0, len = this._keys.length; i < len; i++) { + callback.call(thisArg, this._values[i], this._keys[i]); + } + }; + + return Map; + }()); + + /** + * @constructor + * Represents a join pattern over observable sequences. + */ + function Pattern(patterns) { + this.patterns = patterns; + } + + /** + * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. + * @param other Observable sequence to match in addition to the current pattern. + * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. + */ + Pattern.prototype.and = function (other) { + return new Pattern(this.patterns.concat(other)); + }; + + /** + * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. + * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. + * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + Pattern.prototype.thenDo = function (selector) { + return new Plan(this, selector); + }; + + function Plan(expression, selector) { + this.expression = expression; + this.selector = selector; + } + + Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { + var self = this; + var joinObservers = []; + for (var i = 0, len = this.expression.patterns.length; i < len; i++) { + joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); + } + var activePlan = new ActivePlan(joinObservers, function () { + var result; + try { + result = self.selector.apply(self, arguments); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + }, function () { + for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { + joinObservers[j].removeActivePlan(activePlan); + } + deactivate(activePlan); + }); + for (i = 0, len = joinObservers.length; i < len; i++) { + joinObservers[i].addActivePlan(activePlan); + } + return activePlan; + }; + + function planCreateObserver(externalSubscriptions, observable, onError) { + var entry = externalSubscriptions.get(observable); + if (!entry) { + var observer = new JoinObserver(observable, onError); + externalSubscriptions.set(observable, observer); + return observer; + } + return entry; + } + + function ActivePlan(joinObserverArray, onNext, onCompleted) { + this.joinObserverArray = joinObserverArray; + this.onNext = onNext; + this.onCompleted = onCompleted; + this.joinObservers = new Map(); + for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { + var joinObserver = this.joinObserverArray[i]; + this.joinObservers.set(joinObserver, joinObserver); + } + } + + ActivePlan.prototype.dequeue = function () { + this.joinObservers.forEach(function (v) { v.queue.shift(); }); + }; + + ActivePlan.prototype.match = function () { + var i, len, hasValues = true; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + if (this.joinObserverArray[i].queue.length === 0) { + hasValues = false; + break; + } + } + if (hasValues) { + var firstValues = [], + isCompleted = false; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + firstValues.push(this.joinObserverArray[i].queue[0]); + this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); + } + if (isCompleted) { + this.onCompleted(); + } else { + this.dequeue(); + var values = []; + for (i = 0, len = firstValues.length; i < firstValues.length; i++) { + values.push(firstValues[i].value); + } + this.onNext.apply(this, values); + } + } + }; + + var JoinObserver = (function (__super__) { + inherits(JoinObserver, __super__); + + function JoinObserver(source, onError) { + __super__.call(this); + this.source = source; + this.onError = onError; + this.queue = []; + this.activePlans = []; + this.subscription = new SingleAssignmentDisposable(); + this.isDisposed = false; + } + + var JoinObserverPrototype = JoinObserver.prototype; + + JoinObserverPrototype.next = function (notification) { + if (!this.isDisposed) { + if (notification.kind === 'E') { + return this.onError(notification.exception); + } + this.queue.push(notification); + var activePlans = this.activePlans.slice(0); + for (var i = 0, len = activePlans.length; i < len; i++) { + activePlans[i].match(); + } + } + }; + + JoinObserverPrototype.error = noop; + JoinObserverPrototype.completed = noop; + + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; + + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; + + JoinObserverPrototype.removeActivePlan = function (activePlan) { + this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); + this.activePlans.length === 0 && this.dispose(); + }; + + JoinObserverPrototype.dispose = function () { + __super__.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); + } + }; + + return JoinObserver; + } (AbstractObserver)); + + /** + * Creates a pattern that matches when both observable sequences have an available value. + * + * @param right Observable sequence to match with the current sequence. + * @return {Pattern} Pattern object that matches when both observable sequences have an available value. + */ + observableProto.and = function (right) { + return new Pattern([this, right]); + }; + + /** + * Matches when the observable sequence has an available value and projects the value. + * + * @param {Function} selector Selector that will be invoked for values in the source sequence. + * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + observableProto.thenDo = function (selector) { + return new Pattern([this]).thenDo(selector); + }; + + /** + * Joins together the results from several patterns. + * + * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. + * @returns {Observable} Observable sequence with the results form matching several patterns. + */ + Observable.when = function () { + var len = arguments.length, plans; + if (Array.isArray(arguments[0])) { + plans = arguments[0]; + } else { + plans = new Array(len); + for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } + } + return new AnonymousObservable(function (o) { + var activePlans = [], + externalSubscriptions = new Map(); + var outObserver = observerCreate( + function (x) { o.onNext(x); }, + function (err) { + externalSubscriptions.forEach(function (v) { v.onError(err); }); + o.onError(err); + }, + function (x) { o.onCompleted(); } + ); + try { + for (var i = 0, len = plans.length; i < len; i++) { + activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { + var idx = activePlans.indexOf(activePlan); + activePlans.splice(idx, 1); + activePlans.length === 0 && o.onCompleted(); + })); + } + } catch (e) { + observableThrow(e).subscribe(o); + } + var group = new CompositeDisposable(); + externalSubscriptions.forEach(function (joinObserver) { + joinObserver.subscribe(); + group.add(joinObserver); + }); + + return group; + }); + }; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + return new AnonymousObservable(function (observer) { + var d = dueTime, p = normalizeTime(period); + return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { + if (p > 0) { + var now = scheduler.now(); + d = d + p; + d <= now && (d = now + p); + } + observer.onNext(count); + self(count + 1, d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + return dueTime === period ? + new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }) : + observableDefer(function () { + return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); + }); + } + + /** + * Returns an observable sequence that produces a value after each period. + * + * @example + * 1 - res = Rx.Observable.interval(1000); + * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); + * + * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. + * @returns {Observable} An observable sequence that produces a value after each period. + */ + var observableinterval = Observable.interval = function (period, scheduler) { + return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (isScheduler(periodOrScheduler)) { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + return period === undefined ? + observableTimerTimeSpan(dueTime, scheduler) : + observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(source, dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }, source); + } + + function observableDelayDate(source, dueTime, scheduler) { + return observableDefer(function () { + return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); + }); + } + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * 1 - res = Rx.Observable.delay(new Date()); + * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); + * + * 3 - res = Rx.Observable.delay(5000); + * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); + * @memberOf Observable# + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. + * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delay = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The debounced sequence. + */ + observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; + var subscription = source.subscribe( + function (x) { + hasvalue = true; + value = x; + id++; + var currentId = id, + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { + hasvalue && id === currentId && observer.onNext(value); + hasvalue = false; + })); + }, + function (e) { + cancelable.dispose(); + observer.onError(e); + hasvalue = false; + id++; + }, + function () { + cancelable.dispose(); + hasvalue && observer.onNext(value); + observer.onCompleted(); + hasvalue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }, this); + }; + + /** + * @deprecated use #debounce or #throttleWithTimeout instead. + */ + observableProto.throttle = function(dueTime, scheduler) { + //deprecate('throttle', 'debounce or throttleWithTimeout'); + return this.debounce(dueTime, scheduler); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. + * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + var source = this, timeShift; + timeShiftOrScheduler == null && (timeShift = timeSpan); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (isScheduler(timeShiftOrScheduler)) { + timeShift = timeSpan; + scheduler = timeShiftOrScheduler; + } + return new AnonymousObservable(function (observer) { + var groupDisposable, + nextShift = timeShift, + nextSpan = timeSpan, + q = [], + refCountDisposable, + timerD = new SerialDisposable(), + totalTime = 0; + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable); + + function createTimer () { + var m = new SingleAssignmentDisposable(), + isSpan = false, + isShift = false; + timerD.setDisposable(m); + if (nextSpan === nextShift) { + isSpan = true; + isShift = true; + } else if (nextSpan < nextShift) { + isSpan = true; + } else { + isShift = true; + } + var newTotalTime = isSpan ? nextSpan : nextShift, + ts = newTotalTime - totalTime; + totalTime = newTotalTime; + if (isSpan) { + nextSpan += timeShift; + } + if (isShift) { + nextShift += timeShift; + } + m.setDisposable(scheduler.scheduleWithRelative(ts, function () { + if (isShift) { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + isSpan && q.shift().onCompleted(); + createTimer(); + })); + }; + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe( + function (x) { + for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } + }, + function (e) { + for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } + observer.onError(e); + }, + function () { + for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } + observer.onCompleted(); + } + )); + return refCountDisposable; + }, source); + }; + + /** + * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. + * @param {Number} timeSpan Maximum time length of a window. + * @param {Number} count Maximum element count of a window. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var timerD = new SerialDisposable(), + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable), + n = 0, + windowId = 0, + s = new Subject(); + + function createTimer(id) { + var m = new SingleAssignmentDisposable(); + timerD.setDisposable(m); + m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { + if (id !== windowId) { return; } + n = 0; + var newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(newId); + })); + } + + observer.onNext(addRef(s, refCountDisposable)); + createTimer(0); + + groupDisposable.add(source.subscribe( + function (x) { + var newId = 0, newWindow = false; + s.onNext(x); + if (++n === count) { + newWindow = true; + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + } + newWindow && createTimer(newId); + }, + function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + } + )); + return refCountDisposable; + }, source); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. + * + * @example + * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. + * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. + * + * @example + * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array + * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array + * + * @param {Number} timeSpan Maximum time length of a buffer. + * @param {Number} count Maximum element count of a buffer. + * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { + return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { + return x.toArray(); + }); + }; + + /** + * Records the time interval between consecutive values in an observable sequence. + * + * @example + * 1 - res = source.timeInterval(); + * 2 - res = source.timeInterval(Rx.Scheduler.timeout); + * + * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with time interval information on values. + */ + observableProto.timeInterval = function (scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.map(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { value: x, interval: span }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.default); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.map(function (x) { + return { value: x, timestamp: scheduler.now() }; + }); + }; + + function sampleObservable(source, sampler) { + return new AnonymousObservable(function (o) { + var atEnd = false, value, hasValue = false; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + o.onNext(value); + } + atEnd && o.onCompleted(); + } + + var sourceSubscription = new SingleAssignmentDisposable(); + sourceSubscription.setDisposable(source.subscribe( + function (newValue) { + hasValue = true; + value = newValue; + }, + function (e) { o.onError(e); }, + function () { + atEnd = true; + sourceSubscription.dispose(); + } + )); + + return new CompositeDisposable( + sourceSubscription, + sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe) + ); + }, source); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return typeof intervalOrSampler === 'number' ? + sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : + sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + function createTimer() { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + } + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }, source); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithAbsoluteTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return new Date(); } + * }); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false; + return scheduler.scheduleRecursiveWithAbsoluteAndState(initialState, scheduler.now(), function (state, self) { + hasResult && observer.onNext(state); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + var result = resultSelector(state); + var time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(result, time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false; + return scheduler.scheduleRecursiveWithRelativeAndState(initialState, 0, function (state, self) { + hasResult && observer.onNext(state); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + var result = resultSelector(state); + var time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(result, time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds + * + * @param {Number} dueTime Relative or absolute time shift of the subscription. + * @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) { + var scheduleMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + var d = new SerialDisposable(); + + d.setDisposable(scheduler[scheduleMethod](dueTime, function() { + d.setDisposable(source.subscribe(o)); + })); + + return d; + }, this); + }; + + /** + * 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 (isFunction(subscriptionDelay)) { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable(); + + function start() { + subscription.setDisposable(source.subscribe( + function (x) { + var delay = tryCatch(selector)(x); + if (delay === errorObj) { return observer.onError(delay.e); } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe( + function () { + observer.onNext(x); + delays.remove(d); + done(); + }, + function (e) { observer.onError(e); }, + function () { + observer.onNext(x); + delays.remove(d); + done(); + } + )) + }, + function (e) { observer.onError(e); }, + function () { + atEnd = true; + subscription.dispose(); + done(); + } + )) + } + + function done () { + atEnd && delays.length === 0 && observer.onCompleted(); + } + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start)); + } + + return new CompositeDisposable(subscription, delays); + }, this); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * @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; + 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; + + function setTimer(timeout) { + var myId = id; + + function timerWins () { + return id === myId; + } + + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + timerWins() && subscription.setDisposable(other.subscribe(observer)); + d.dispose(); + }, function (e) { + timerWins() && observer.onError(e); + }, function () { + timerWins() && subscription.setDisposable(other.subscribe(observer)); + })); + }; + + setTimer(firstTimeout); + + function observerWins() { + 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(isPromise(timeout) ? observableFromPromise(timeout) : timeout); + } + }, function (e) { + observerWins() && observer.onError(e); + }, function () { + observerWins() && observer.onCompleted(); + })); + return new CompositeDisposable(subscription, timer); + }, source); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The debounced sequence. + */ + observableProto.debounceWithSelector = function (durationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; + var subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = durationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + + isPromise(throttle) && (throttle = observableFromPromise(throttle)); + + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + hasValue && id === currentid && observer.onNext(value); + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + hasValue && id === currentid && observer.onNext(value); + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + hasValue && observer.onNext(value); + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }, source); + }; + + /** + * @deprecated use #debounceWithSelector instead. + */ + observableProto.throttleWithSelector = function (durationSelector) { + //deprecate('throttleWithSelector', 'debounceWithSelector'); + return this.debounceWithSelector(durationSelector); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (o) { + 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) { + o.onNext(q.shift().value); + } + }, function (e) { o.onError(e); }, function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + o.onNext(q.shift().value); + } + o.onCompleted(); + }); + }, source); + }; + + /** + * 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. + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + 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(); + } + }, function (e) { o.onError(e); }, function () { + var now = scheduler.now(); + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { o.onNext(next.value); } + } + o.onCompleted(); + }); + }, source); + }; + + /** + * 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. + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + 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(); + } + }, function (e) { o.onError(e); }, function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + now - next.interval <= duration && res.push(next.value); + } + o.onNext(res); + o.onCompleted(); + }); + }, source); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); + }, source); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false; + return new CompositeDisposable( + scheduler.scheduleWithRelative(duration, function () { open = true; }), + source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); + }, source); + }; + + /** + * 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(), [scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [scheduler]); + * @param {Date|Number} 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] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (o) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && o.onNext(x); }, + function (e) { o.onError(e); }, function () { o.onCompleted(); })); + }, source); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (o) { + return new CompositeDisposable( + scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), + source.subscribe(o)); + }, source); + }; + + /** + * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. + * @param {Number} windowDuration time to wait before emitting another item after emitting the last item + * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. + * @returns {Observable} An Observable that performs the throttle operation. + */ + observableProto.throttleFirst = function (windowDuration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var duration = +windowDuration || 0; + if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } + var source = this; + return new AnonymousObservable(function (o) { + var lastOnNext = 0; + return source.subscribe( + function (x) { + var now = scheduler.now(); + if (lastOnNext === 0 || now - lastOnNext >= duration) { + lastOnNext = now; + o.onNext(x); + } + },function (e) { o.onError(e); }, function () { o.onCompleted(); } + ); + }, source); + }; + + /** + * Executes a transducer to transform the observable sequence + * @param {Transducer} transducer A transducer to execute + * @returns {Observable} An Observable sequence containing the results from the transducer. + */ + observableProto.transduce = function(transducer) { + var source = this; + + function transformForObserver(o) { + return { + '@@transducer/init': function() { + return o; + }, + '@@transducer/step': function(obs, input) { + return obs.onNext(input); + }, + '@@transducer/result': function(obs) { + return obs.onCompleted(); + } + }; + } + + return new AnonymousObservable(function(o) { + var xform = transducer(transformForObserver(o)); + return source.subscribe( + function(v) { + try { + xform['@@transducer/step'](o, v); + } catch (e) { + o.onError(e); + } + }, + function (e) { o.onError(e); }, + function() { xform['@@transducer/result'](o); } + ); + }, source); + }; + + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }, this); + }; + + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this, + selectorFunc = bindCallback(selector, thisArg, 3); + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selectorFunc(x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + function (e) { observer.onError(e); }, + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + function (e) { observer.onError(e); }, + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }, this); + }; + + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (__super__) { + + function localNow() { + return this.toDateTimeOffset(this.clock); + } + + function scheduleNow(state, action) { + return this.scheduleAbsoluteWithState(state, this.clock, action); + } + + function scheduleRelative(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + inherits(VirtualTimeScheduler, __super__); + + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function VirtualTimeScheduler(initialClock, comparer) { + this.clock = initialClock; + this.comparer = comparer; + this.isEnabled = false; + this.queue = new PriorityQueue(1024); + __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; + + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelative = notImplemented; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsoluteWithState(state, runAt, action); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { + return this.scheduleRelativeWithState(action, dueTime, invokeAction); + }; + + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + } + }; + + /** + * Stops the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.stop = function () { + this.isEnabled = false; + }; + + /** + * Advances the scheduler's clock to the specified time, running all work till that point. + * @param {Number} time Absolute time to advance the scheduler's clock to. + */ + VirtualTimeSchedulerPrototype.advanceTo = function (time) { + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } + if (dueToClock === 0) { return; } + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + this.clock = time; + } + }; + + /** + * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.advanceBy = function (time) { + var dt = this.add(this.clock, time), + dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } + if (dueToClock === 0) { return; } + + this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } + + this.clock = dt; + }; + + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + while (this.queue.length > 0) { + var next = this.queue.peek(); + if (next.isCancelled()) { + this.queue.dequeue(); + } else { + return next; + } + } + return null; + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Scheduler} scheduler Scheduler to execute the action on. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { + return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { + var self = this; + + function run(scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + } + + var si = new ScheduledItem(this, state, run, dueTime, this.comparer); + this.queue.enqueue(si); + + return si.disposable; + }; + + return VirtualTimeScheduler; + }(Scheduler)); + + /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ + Rx.HistoricalScheduler = (function (__super__) { + inherits(HistoricalScheduler, __super__); + + /** + * Creates a new historical scheduler with the specified initial clock value. + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function HistoricalScheduler(initialClock, comparer) { + var clock = initialClock == null ? 0 : initialClock; + var cmp = comparer || defaultSubComparer; + __super__.call(this, clock, cmp); + } + + var HistoricalSchedulerProto = HistoricalScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + HistoricalSchedulerProto.add = function (absolute, relative) { + return absolute + relative; + }; + + HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @memberOf HistoricalScheduler + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + HistoricalSchedulerProto.toRelative = function (timeSpan) { + return timeSpan; + }; + + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); + + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + return subscriber && isFunction(subscriber.dispose) ? subscriber : + isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; + } + + function setDisposable(s, state) { + var ado = state[0], subscribe = state[1]; + var sub = tryCatch(subscribe)(ado); + + if (sub === errorObj) { + if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } + } + ado.setDisposable(fixSubscriber(sub)); + } + + function AnonymousObservable(subscribe, parent) { + this.source = parent; + + function s(observer) { + var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; + + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.scheduleWithState(state, setDisposable); + } else { + setDisposable(null, state); + } + return ado; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + var AutoDetachObserver = (function (__super__) { + inherits(AutoDetachObserver, __super__); + + function AutoDetachObserver(observer) { + __super__.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var result = tryCatch(this.observer.onNext).call(this.observer, value); + if (result === errorObj) { + this.dispose(); + thrower(result.e); + } + }; + + AutoDetachObserverPrototype.error = function (err) { + var result = tryCatch(this.observer.onError).call(this.observer, err); + this.dispose(); + result === errorObj && thrower(result.e); + }; + + AutoDetachObserverPrototype.completed = function () { + var result = tryCatch(this.observer.onCompleted).call(this.observer); + this.dispose(); + result === errorObj && thrower(result.e); + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; + + AutoDetachObserverPrototype.dispose = function () { + __super__.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + var GroupedObservable = (function (__super__) { + inherits(GroupedObservable, __super__); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + __super__.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (__super__) { + function subscribe(observer) { + checkDisposed(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.hasError) { + observer.onError(this.error); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, __super__); + + /** + * Creates a subject. + */ + function Subject() { + __super__.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + this.hasError = false; + } + + addProperties(Subject.prototype, Observer.prototype, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { return this.observers.length > 0; }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers.length = 0; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers.length = 0; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (!this.isStopped) { + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (__super__) { + + function subscribe(observer) { + checkDisposed(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + if (this.hasError) { + observer.onError(this.error); + } else if (this.hasValue) { + observer.onNext(this.value); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, __super__); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + __super__.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.hasValue = false; + this.observers = []; + this.hasError = false; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var i, len; + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + var os = cloneArray(this.observers), len = os.length; + + if (this.hasValue) { + for (i = 0; i < len; i++) { + var o = os[i]; + o.onNext(this.value); + o.onCompleted(); + } + } else { + for (i = 0; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers.length = 0; + } + }, + /** + * Notifies all subscribed observers about the error. + * @param {Mixed} error The Error to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + this.hasError = true; + this.error = error; + + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers.length = 0; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + this.value = value; + this.hasValue = true; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { + inherits(AnonymousSubject, __super__); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + function AnonymousSubject(observer, observable) { + this.observer = observer; + this.observable = observable; + __super__.call(this, subscribe); + } + + addProperties(AnonymousSubject.prototype, Observer.prototype, { + onCompleted: function () { + this.observer.onCompleted(); + }, + onError: function (error) { + this.observer.onError(error); + }, + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + /** + * Used to pause and resume streams. + */ + Rx.Pauser = (function (__super__) { + inherits(Pauser, __super__); + + function Pauser() { + __super__.call(this); + } + + /** + * Pauses the underlying sequence. + */ + Pauser.prototype.pause = function () { this.onNext(false); }; + + /** + * Resumes the underlying sequence. + */ + Pauser.prototype.resume = function () { this.onNext(true); }; + + return Pauser; + }(Subject)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } + + // All code before this point will be filtered from stack traces. + var rEndingLine = captureLine(); + +}.call(this)); + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":2}],117:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cyclejs = require('cyclejs'); + +var _cyclejs2 = _interopRequireDefault(_cyclejs); + +var Rx = _cyclejs2['default'].Rx; +var packageJson = require('package'); +var RxPackageJson = require('cyclejs/node_modules/rx/package.json'); + +var DEFAULT_EXAMPLE = 'merge'; + +module.exports = function appModel() { + return { + route$: Rx.Observable.fromEvent(window, 'hashchange').map(function (hashEvent) { + return hashEvent.target.location.hash.replace('#', ''); + }).startWith(window.location.hash.replace('#', '') || DEFAULT_EXAMPLE), + appVersion$: Rx.Observable.just(packageJson.version), + rxVersion$: Rx.Observable.just(RxPackageJson.version) + }; +}; +},{"cyclejs":5,"cyclejs/node_modules/rx/package.json":64,"package":115}],118:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cyclejs = require('cyclejs'); + +var _cyclejs2 = _interopRequireDefault(_cyclejs); + +var _rxmarblesStylesColors = require('rxmarbles/styles/colors'); + +var _rxmarblesStylesColors2 = _interopRequireDefault(_rxmarblesStylesColors); + +var _rxmarblesStylesDimens = require('rxmarbles/styles/dimens'); + +var _rxmarblesStylesDimens2 = _interopRequireDefault(_rxmarblesStylesDimens); + +var _rxmarblesStylesFonts = require('rxmarbles/styles/fonts'); + +var _rxmarblesStylesFonts2 = _interopRequireDefault(_rxmarblesStylesFonts); + +var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + +var Rx = _cyclejs2['default'].Rx; +var h = _cyclejs2['default'].h; + +var rxmarblesGithubUrl = 'https://github.com/staltz/rxmarbles'; +var rxjsGithubUrl = 'https://github.com/Reactive-Extensions/RxJS'; + +var pageRowWidth = '1060px'; +var sandboxWidth = '820px'; + +var pageRowStyle = { + position: 'relative', + width: pageRowWidth, + margin: '0 auto' +}; + +var pageRowChildStyle = { + display: 'inline-block', + marginLeft: '-' + _rxmarblesStylesDimens2['default'].spaceMedium +}; + +var pageRowFirstChildStyle = (0, _rxmarblesStylesUtils.mergeStyles)(pageRowChildStyle, { + width: 'calc(' + pageRowWidth + ' - ' + sandboxWidth + ' - ' + _rxmarblesStylesDimens2['default'].spaceMedium + ')', + marginRight: _rxmarblesStylesDimens2['default'].spaceMedium +}); + +var pageRowLastChildStyle = (0, _rxmarblesStylesUtils.mergeStyles)(pageRowChildStyle, { + width: sandboxWidth +}); + +function vrenderHeader() { + return h('div', { style: pageRowStyle }, [h('h1', { style: (0, _rxmarblesStylesUtils.mergeStyles)({ + fontFamily: _rxmarblesStylesFonts2['default'].fontSpecial, + color: _rxmarblesStylesColors2['default'].greyDark }, pageRowFirstChildStyle) }, 'RxMarbles'), h('h3', { style: (0, _rxmarblesStylesUtils.mergeStyles)({ + color: _rxmarblesStylesColors2['default'].greyDark }, pageRowLastChildStyle) }, 'Interactive diagrams of Rx Observables')]); +} + +function vrenderContent(route) { + return h('div', { style: (0, _rxmarblesStylesUtils.mergeStyles)(pageRowStyle, { marginTop: _rxmarblesStylesDimens2['default'].spaceSmall }) }, [h('div', { style: pageRowFirstChildStyle }, h('x-operators-menu', { key: 'operatorsMenu' })), h('div', { style: (0, _rxmarblesStylesUtils.mergeStyles)({ + position: 'absolute', + top: '0' }, pageRowLastChildStyle) }, h('x-sandbox', { key: 'sandbox', route: route, width: '820px', showSubscriptions: true }))]); +} + +function vrenderFooter(appVersion, rxVersion) { + return h('section', { + style: { + position: 'fixed', + bottom: '2px', + right: _rxmarblesStylesDimens2['default'].spaceMedium, + color: _rxmarblesStylesColors2['default'].greyDark + } + }, [h('a', { href: '' + rxmarblesGithubUrl + '/releases/tag/v' + appVersion }, 'v' + appVersion), ' built on ', h('a', { href: '' + rxjsGithubUrl + '/tree/v' + rxVersion }, 'RxJS v' + rxVersion), ' by ', h('a', { href: 'https://twitter.com/andrestaltz' }, '@andrestaltz')]); +} + +module.exports = function appView(model) { + return Rx.Observable.combineLatest(model.route$, model.appVersion$, model.rxVersion$, function (route, appVersion, rxVersion) { + return h('div', [vrenderHeader(), vrenderContent(route), vrenderFooter(appVersion, rxVersion)]); + }); +}; +},{"cyclejs":5,"rxmarbles/styles/colors":138,"rxmarbles/styles/dimens":139,"rxmarbles/styles/fonts":140,"rxmarbles/styles/utils":141}],119:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cyclejs = require('cyclejs'); + +var _cyclejs2 = _interopRequireDefault(_cyclejs); + +var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + +var Rx = _cyclejs2['default'].Rx; +var h = _cyclejs2['default'].h; + +function createContainerStyle(inputStyle) { + return { + display: 'inline-block', + position: 'relative', + width: 'calc(8 * ' + inputStyle.thickness + ')', + height: inputStyle.height, + margin: '0 calc(-4 * ' + inputStyle.thickness + ')' + }; +} + +function createInnerStyle(inputStyle) { + return { + width: inputStyle.thickness, height: '50%', marginLeft: 'calc(3.5 * ' + inputStyle.thickness + ')', marginTop: 'calc(' + inputStyle.height + ' / 4.0)', @@ -20278,10 +31025,10 @@ function render(time, isDraggable, isTall, inputStyle, isHighlighted) { var containerStyle = createContainerStyle(inputStyle); var innerStyle = createInnerStyle(inputStyle); return h('div.completionRoot', { - style: _rxmarblesStylesUtils.mergeStyles({ + style: (0, _rxmarblesStylesUtils.mergeStyles)({ left: '' + time + '%' }, containerStyle, isDraggable ? draggableContainerStyle : {}) }, [h('div.completionInner', { - style: _rxmarblesStylesUtils.mergeStyles(innerStyle, isDraggable && isHighlighted ? _rxmarblesStylesUtils.elevation1Style : null, isTall ? innerTallStyle : null) + style: (0, _rxmarblesStylesUtils.mergeStyles)(innerStyle, isDraggable && isHighlighted ? _rxmarblesStylesUtils.elevation1Style : null, isTall ? innerTallStyle : null) })]); } @@ -20417,7 +31164,8 @@ function applyChangeMarbleTime(diagramData, marbleDelta) { } function applyChangeEndTime(diagramData, endDelta) { - return diagramData.set('end', diagramData.get('end') + endDelta); + var newEnd = diagramData.get('end') + endDelta; + return diagramData.set('end', newEnd).set('eventualEnd', newEnd); } function applyMarbleDataConstraints(marbleData) { @@ -20435,7 +31183,7 @@ function applyEndTimeConstraint(diagramData) { newEndTime = Math.round(newEndTime); newEndTime = Math.min(newEndTime, 100); newEndTime = Math.max(0, newEndTime); - return diagramData.set('end', newEndTime); + return diagramData.set('end', newEndTime).set('eventualEnd', newEndTime); } function applyDiagramDataConstraints(diagramData) { @@ -20476,7 +31224,9 @@ function diagramModel(properties, intent) { return { data$: data$, newData$: makeNewDiagramData$(data$, intent.changeMarbleTime$, intent.changeEndTime$, properties.get('interactive')), - isInteractive$: properties.get('interactive').startWith(false) + isInteractive$: properties.get('interactive').startWith(false), + isCompact$: properties.get('compact').startWith(false), + showGhost$: properties.get('ghost').startWith(false) }; } @@ -20513,93 +31263,171 @@ var h = _cyclejs2['default'].h; var MARBLE_WIDTH = 5; // estimate of a marble width, in percentages var diagramSidePadding = _rxmarblesStylesDimens2['default'].spaceMedium; -var diagramVerticalMargin = _rxmarblesStylesDimens2['default'].spaceLarge; var diagramArrowThickness = '2px'; var diagramArrowSidePadding = _rxmarblesStylesDimens2['default'].spaceLarge; var diagramArrowHeadSize = '8px'; var diagramArrowColor = _rxmarblesStylesColors2['default'].black; +var diagramArrowColorGhost = _rxmarblesStylesColors2['default'].almostWhite; var diagramMarbleSize = _rxmarblesStylesDimens2['default'].spaceLarge; var diagramCompletionHeight = '44px'; -var diagramStyle = _rxmarblesStylesUtils.mergeStyles({ - position: 'relative', - display: 'block', - width: '100%', - height: 'calc(' + diagramMarbleSize + ' + 2 * ' + diagramVerticalMargin + ')', - overflow: 'visible', - cursor: 'default' }, _rxmarblesStylesUtils.textUnselectable); - -var diagramBodyStyle = { - position: 'absolute', - left: 'calc(' + diagramArrowSidePadding + ' + ' + diagramSidePadding + '\n + (' + diagramMarbleSize + ' / 2))', - right: 'calc(' + diagramArrowSidePadding + ' + ' + diagramSidePadding + '\n + (' + diagramMarbleSize + ' / 2))', - top: 'calc(' + diagramVerticalMargin + ' + (' + diagramMarbleSize + ' / 2))', - height: diagramCompletionHeight, - marginTop: 'calc(0px - (' + diagramCompletionHeight + ' / 2))' -}; +function diagramVerticalMargin(isCompact) { + return isCompact ? _rxmarblesStylesDimens2['default'].spaceSmall : _rxmarblesStylesDimens2['default'].spaceLarge; +} -function renderMarble(marbleData) { - var isDraggable = arguments[1] === undefined ? false : arguments[1]; +function diagramStyle(isCompact) { + return (0, _rxmarblesStylesUtils.mergeStyles)({ + position: 'relative', + display: 'block', + width: '100%', + height: 'calc(' + diagramMarbleSize + ' + 2 * ' + diagramVerticalMargin(isCompact) + ')', + overflow: 'visible', + cursor: 'default' + }, _rxmarblesStylesUtils.textUnselectable); +} - return h('x-marble.diagramMarble', { - key: 'marble' + marbleData.get('id'), - data: marbleData, - isDraggable: isDraggable, - style: { size: diagramMarbleSize } - }); +var paddingToTimeline = '(' + diagramArrowSidePadding + ' + ' + diagramSidePadding + ' + (' + diagramMarbleSize + ' / 2))'; +var timelineSize = '(100% - (2 * ' + paddingToTimeline + '))'; +function timeLeftPosition(time) { + return '(' + paddingToTimeline + ' + (' + timelineSize + ' * ' + time / 100 + '))'; +} +function timeRightPosition(time) { + return '(' + paddingToTimeline + ' + (' + timelineSize + ' * ' + (100 - time) / 100 + '))'; } -function renderCompletion(diagramData) { - var isDraggable = arguments[1] === undefined ? false : arguments[1]; +function diagramBodyStyle(isCompact) { + return { + position: 'absolute', + left: 'calc(' + paddingToTimeline + ')', + right: 'calc(' + paddingToTimeline + ')', + top: 'calc(' + diagramVerticalMargin(isCompact) + ' + (' + diagramMarbleSize + ' / 2))', + height: diagramCompletionHeight, + marginTop: 'calc(0px - (' + diagramCompletionHeight + ' / 2))' + }; +} + +function renderMarble(marbleData, isDraggable, showGhost, isGhost) { + if (!isGhost || showGhost) { + return h('x-marble.diagramMarble', { + key: 'marble' + marbleData.get('id'), + data: marbleData, + isDraggable: isDraggable, + style: { size: diagramMarbleSize }, + isGhost: isGhost + }); + } +} + +function renderEndpoints(diagramData, isDraggable, showGhost) { + var endpoints = [renderEndpoint(diagramData, 'start', 'diagramStart', false, false), renderEndpoint(diagramData, 'end', 'diagramCompletion', isDraggable, false)]; + + // add the eventualEndpoint if it is past the actual end + if (diagramData.get('eventualEnd') > diagramData.get('end')) { + endpoints.push(renderEndpoint(diagramData, 'eventualEnd', 'diagramEventualEnd', false, showGhost)); + } + + return endpoints; +} + +function renderEndpoint(diagramData, timeName, endpointType, isDraggable, isGhost) { + var endTime = diagramData.get(timeName); + // do not render if the time is not defined, or it was at the end of our simulation (and is not draggable) + if (endTime === undefined || endTime > 100 || !isDraggable && endTime === 100) { + return undefined; + } + + var color = isGhost ? diagramArrowColorGhost : diagramArrowColor; - var endTime = diagramData.get('end'); var isTall = diagramData.get('notifications').some(function (marbleData) { - return Math.abs(marbleData.get('time') - diagramData.get('end')) <= MARBLE_WIDTH * 0.5; + return Math.abs(marbleData.get('time') - endTime) <= MARBLE_WIDTH * 0.5; }); - return h('x-diagram-completion.diagramCompletion', { - key: 'completion', + return h('x-diagram-completion.' + endpointType, { + key: endpointType, time: endTime, isDraggable: isDraggable, isTall: isTall, style: { thickness: diagramArrowThickness, - color: diagramArrowColor, + color: color, height: diagramCompletionHeight } }); } -function renderDiagramArrow() { - return h('div.diagramArrow', { style: { - backgroundColor: diagramArrowColor, - height: diagramArrowThickness, - position: 'absolute', - top: 'calc(' + diagramVerticalMargin + ' + (' + diagramMarbleSize + ' / 2))', - left: diagramSidePadding, - right: diagramSidePadding - } }); +function renderDiagramArrow(data, isCompact, showGhost) { + /* render the line in 3 segments: + * - to the left of 'start' render ghosted + * - render between start & end normal + * - to the right of 'end' render ghosted + */ + var arrowStyle = { + height: diagramArrowThickness, + position: 'absolute', + top: 'calc(' + diagramVerticalMargin(isCompact) + ' + (' + diagramMarbleSize + ' / 2))' + }; + var sections = []; + var start = data.get('start'); + var end = data.get('end'); + var middleStart = diagramSidePadding; + var middleEnd = diagramSidePadding; + + if (showGhost) { + sections.push(h('div.diagramArrow', { + style: (0, _rxmarblesStylesUtils.mergeStyles)(arrowStyle, { + backgroundColor: diagramArrowColorGhost, + left: middleStart, + right: 'calc(' + timeRightPosition(start) + ')' + }) + })); + middleStart = 'calc(' + timeLeftPosition(start) + ')'; + + if (end < 100) { + sections.push(h('div.diagramArrow', { + style: (0, _rxmarblesStylesUtils.mergeStyles)(arrowStyle, { + backgroundColor: diagramArrowColorGhost, + left: 'calc(' + timeLeftPosition(end) + ')', + right: middleEnd + }) + })); + middleEnd = 'calc(' + timeRightPosition(end) + ')'; + } + } + + if (!showGhost || start < end) { + sections.push(h('div.diagramArrow', { + style: (0, _rxmarblesStylesUtils.mergeStyles)(arrowStyle, { + backgroundColor: diagramArrowColor, + left: middleStart, + right: middleEnd + }) + })); + } + + return sections; } -function renderDiagramArrowHead() { +function renderDiagramArrowHead(data, isCompact, showGhost) { + var end = data.get('end'); + var isGhost = end < 100; + var color = showGhost && isGhost ? diagramArrowColorGhost : diagramArrowColor; return h('div.diagramArrowHead', { style: { width: 0, height: 0, borderTop: '' + diagramArrowHeadSize + ' solid transparent', borderBottom: '' + diagramArrowHeadSize + ' solid transparent', - borderLeft: 'calc(2 * ' + diagramArrowHeadSize + ') solid ' + diagramArrowColor, + borderLeft: 'calc(2 * ' + diagramArrowHeadSize + ') solid ' + color, display: 'inline-block', right: 'calc(' + diagramSidePadding + ' - 1px)', position: 'absolute', - top: 'calc(' + diagramVerticalMargin + ' + (' + diagramMarbleSize + ' / 2)\n - ' + diagramArrowHeadSize + ' + (' + diagramArrowThickness + ' / 2))' + top: 'calc(' + diagramVerticalMargin(isCompact) + ' + (' + diagramMarbleSize + ' / 2)\n - ' + diagramArrowHeadSize + ' + (' + diagramArrowThickness + ' / 2))' } }); } -function renderDiagram(data, isInteractive) { +function renderDiagram(data, isInteractive, isCompact, showGhost) { var marblesVTree = data.get('notifications').map(function (notification) { - return renderMarble(notification, isInteractive); + return renderMarble(notification, isInteractive, showGhost, notification.get('time') > data.get('end') + 0.01); }).toArray(); // from Immutable.List - var completionVTree = renderCompletion(data, isInteractive); - return h('div', { style: diagramStyle }, [renderDiagramArrow(), renderDiagramArrowHead(), h('div', { style: diagramBodyStyle }, [completionVTree].concat(marblesVTree))]); + return h('div', { style: diagramStyle(isCompact) }, [renderDiagramArrow(data, isCompact, showGhost), renderDiagramArrowHead(data, isCompact, showGhost), h('div', { style: diagramBodyStyle(isCompact) }, renderEndpoints(data, isInteractive, showGhost).concat(marblesVTree))]); } function sanitizeDiagramItem(x) { @@ -20629,7 +31457,7 @@ function animateData$(data$) { }); return { - v: _rxtween2['default'](animConf).map(function (x) { + v: (0, _rxtween2['default'])(animConf).map(function (x) { return data.update('notifications', function (notifications) { return notifications.zipWith(function (n1, n2) { return n1.update('time', function (t1) { @@ -20649,7 +31477,7 @@ function animateData$(data$) { function diagramView(model) { return { - vtree$: Rx.Observable.combineLatest(animateData$(model.data$).merge(model.newData$), model.isInteractive$, renderDiagram) + vtree$: Rx.Observable.combineLatest(animateData$(model.data$).merge(model.newData$), model.isInteractive$, model.isCompact$, model.showGhost$, renderDiagram) }; } @@ -20676,9 +31504,9 @@ var _rxmarblesComponentsDiagramDiagramIntent = require('rxmarbles/components/dia var _rxmarblesComponentsDiagramDiagramIntent2 = _interopRequireDefault(_rxmarblesComponentsDiagramDiagramIntent); function DiagramComponent(interactions, properties) { - var intent = _rxmarblesComponentsDiagramDiagramIntent2['default'](interactions); - var model = _rxmarblesComponentsDiagramDiagramModel2['default'](properties, intent); - var view = _rxmarblesComponentsDiagramDiagramView2['default'](model); + var intent = (0, _rxmarblesComponentsDiagramDiagramIntent2['default'])(interactions); + var model = (0, _rxmarblesComponentsDiagramDiagramModel2['default'])(properties, intent); + var view = (0, _rxmarblesComponentsDiagramDiagramView2['default'])(model); return { vtree$: view.vtree$, @@ -20721,17 +31549,17 @@ function createContainerStyle(inputStyle) { }; } -function renderSvg(data, isDraggable, inputStyle, isHighlighted) { +function renderSvg(data, isDraggable, inputStyle, isHighlighted, isGhost) { var POSSIBLE_COLORS = [_rxmarblesStylesColors2['default'].blue, _rxmarblesStylesColors2['default'].green, _rxmarblesStylesColors2['default'].yellow, _rxmarblesStylesColors2['default'].red]; - var color = POSSIBLE_COLORS[data.get('id') % POSSIBLE_COLORS.length]; - return _cyclejsNode_modulesVirtualDomVirtualHyperscriptSvg2['default']('svg.marbleShape', { - style: _rxmarblesStylesUtils.mergeStyles({ + var color = isGhost ? _rxmarblesStylesColors2['default'].almostWhite : POSSIBLE_COLORS[data.get('id') % POSSIBLE_COLORS.length]; + return (0, _cyclejsNode_modulesVirtualDomVirtualHyperscriptSvg2['default'])('svg.marbleShape', { + style: (0, _rxmarblesStylesUtils.mergeStyles)({ overflow: 'visible', width: inputStyle.size, height: inputStyle.size }, isDraggable && isHighlighted ? _rxmarblesStylesUtils.svgElevation1Style : {}), - attributes: { viewBox: '0 0 1 1' } }, [_cyclejsNode_modulesVirtualDomVirtualHyperscriptSvg2['default']('circle', { + attributes: { viewBox: '0 0 1 1' } }, [(0, _cyclejsNode_modulesVirtualDomVirtualHyperscriptSvg2['default'])('circle', { style: { - stroke: _rxmarblesStylesColors2['default'].black, + stroke: isGhost ? _rxmarblesStylesColors2['default'].greyLight : _rxmarblesStylesColors2['default'].black, fill: color }, attributes: { @@ -20741,29 +31569,36 @@ function renderSvg(data, isDraggable, inputStyle, isHighlighted) { })]); } -function renderInnerContent(data, inputStyle) { +function renderInnerContent(data, inputStyle, isGhost) { + var style = { + position: 'absolute', + width: '100%', + height: '100%', + top: '0', + margin: '0', + textAlign: 'center', + lineHeight: inputStyle.size + }; + + if (isGhost) { + style['color'] = _rxmarblesStylesColors2['default'].greyLight; + } + return h('p.marbleContent', { - style: _rxmarblesStylesUtils.mergeStyles({ - position: 'absolute', - width: '100%', - height: '100%', - top: '0', - margin: '0', - textAlign: 'center', - lineHeight: inputStyle.size }, _rxmarblesStylesUtils.textUnselectable) + style: (0, _rxmarblesStylesUtils.mergeStyles)(style, _rxmarblesStylesUtils.textUnselectable) }, '' + data.get('content')); } -function render(data, isDraggable, inputStyle, isHighlighted) { +function render(data, isDraggable, inputStyle, isHighlighted, isGhost) { var draggableContainerStyle = { cursor: 'ew-resize' }; return h('div.marbleRoot', { - style: _rxmarblesStylesUtils.mergeStyles({ + style: (0, _rxmarblesStylesUtils.mergeStyles)({ left: '' + data.get('time') + '%', zIndex: data.get('time') }, createContainerStyle(inputStyle), isDraggable ? draggableContainerStyle : null), attributes: { 'data-marble-id': data.get('id') } - }, [renderSvg(data, isDraggable, inputStyle, isHighlighted), renderInnerContent(data, inputStyle)]); + }, [renderSvg(data, isDraggable, inputStyle, isHighlighted, isGhost), renderInnerContent(data, inputStyle, isGhost)]); } function marbleComponent(interactions, properties) { @@ -20771,6 +31606,7 @@ function marbleComponent(interactions, properties) { var stopHighlight$ = interactions.get('.marbleRoot', 'mouseleave'); var data$ = properties.get('data'); var isDraggable$ = properties.get('isDraggable').startWith(false); + var isGhost$ = properties.get('isGhost').startWith(false); var style$ = properties.get('style').startWith({}); var isHighlighted$ = Rx.Observable.merge(startHighlight$.map(function () { return true; @@ -20779,7 +31615,7 @@ function marbleComponent(interactions, properties) { })).startWith(false); return { - vtree$: Rx.Observable.combineLatest(data$, isDraggable$, style$, isHighlighted$, render) + vtree$: Rx.Observable.combineLatest(data$, isDraggable$, style$, isHighlighted$, isGhost$, render) }; } @@ -20828,7 +31664,7 @@ function operatorsMenuLink(interactions, properties) { }, '❯'); var vtree$ = Rx.Observable.combineLatest(href$, content$, isHighlighted$, function (href, content, isHighlighted) { return h('a.link', { - style: _rxmarblesStylesUtils.mergeStyles({ + style: (0, _rxmarblesStylesUtils.mergeStyles)({ position: 'relative', display: 'block', color: _rxmarblesStylesColors2['default'].greyDark }, isHighlighted ? { color: _rxmarblesStylesColors2['default'].black } : null), @@ -20915,7 +31751,7 @@ function renderExampleItems(examples) { function renderExampleCategory(categoryName, isFirstCategory) { return h('li', { - style: _rxmarblesStylesUtils.mergeStyles(operatorsMenuCategoryStyle, isFirstCategory ? { marginTop: '0' } : {}) }, '' + categoryName); + style: (0, _rxmarblesStylesUtils.mergeStyles)(operatorsMenuCategoryStyle, isFirstCategory ? { marginTop: '0' } : {}) }, '' + categoryName); } function renderMenuContent(categoryMap) { @@ -20953,14 +31789,13 @@ function operatorsMenuComponent() { module.exports = operatorsMenuComponent; },{"cyclejs":5,"rxmarbles/data/examples":134,"rxmarbles/styles/colors":138,"rxmarbles/styles/dimens":139,"rxmarbles/styles/utils":141}],127:[function(require,module,exports){ -'use strict'; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - /* * Functions to handle data of input diagrams in the example shown in the * sandbox. */ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _cyclejs = require('cyclejs'); @@ -20992,9 +31827,10 @@ function prepareInputDiagram(diagram) { var indexInDiagramArray = arguments[1] === undefined ? 0 : arguments[1]; var last = diagram[diagram.length - 1]; - return _immutable2['default'].Map({}).set('notifications', getNotifications(diagram).map(function (notification) { + var end = typeof last === 'number' ? last : 100; + return _immutable2['default'].Map({ start: 0 }).set('notifications', getNotifications(diagram).map(function (notification) { return prepareNotification(notification, indexInDiagramArray); - })).set('end', typeof last === 'number' ? last : 100).set('id', indexInDiagramArray); + })).set('end', end).set('eventualEnd', end).set('id', indexInDiagramArray); } function augmentWithExampleKey(diagramData, exampleKey) { @@ -21036,14 +31872,13 @@ module.exports = { makeNewInputDiagramsData$: makeNewInputDiagramsData$ }; },{"cyclejs":5,"immutable":114,"rxmarbles/components/sandbox/utils":130}],128:[function(require,module,exports){ -'use strict'; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - /* * Functions to handle data of the output diagram in the example shown in the * sandbox. */ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _cyclejs = require('cyclejs'); @@ -21079,70 +31914,160 @@ function makeScheduler() { return scheduler; } -function justIncomplete(item, scheduler) { - return new _cyclejs.Rx.AnonymousObservable(function (observer) { - return scheduler.schedule(function () { - observer.onNext(item); +/** + * Creates an (virtual time) Rx.Observable from diagram + * data (array of data items). + */ +function toVTStream(diagramData, scheduler) { + return _cyclejs.Rx.Observable.create(function (observer) { + var notifications = diagramData.get('notifications').map(function (item) { + return scheduler.scheduleWithRelative(item.get('time'), function () { + return observer.onNext(item); + }); + }).toArray(); + var completion = scheduler.scheduleWithRelative(diagramData.get('end') + 0.01, function () { + return observer.onCompleted(); }); + var s = new _cyclejs.Rx.CompositeDisposable(notifications); + s.add(completion); + return s; }); } /** - * Creates an (virtual time) Rx.Observable from diagram - * data (array of data items). + * Wraps the observable and collects usage information + * Each time the observable is subscribed, produces a notification stream that shows + * - when the subscription started + * - each notification produced + * - when the subscription ended + * - any remaining notifications that would have occurred had the subscription continued + * @param stream + * @param scheduler + * @param correctedMaxTime */ -function toVTStream(diagramData, scheduler) { - var singleMarbleStreams = diagramData.get('notifications').map(function (item) { - return justIncomplete(item, scheduler).delay(item.get('time'), scheduler); - }).toArray(); - // Necessary correction to include marbles at time exactly diagramData.end: - var correctedEndTime = diagramData.get('end') + 0.01; - return _cyclejs.Rx.Observable.merge(singleMarbleStreams).takeUntilWithTime(correctedEndTime, scheduler).publish().refCount(); +function observeUsage(stream, scheduler, correctedMaxTime) { + var subject = new _cyclejs.Rx.Subject(); + var diagrams = subject.takeUntilWithTime(new Date(correctedMaxTime), scheduler); + var newStream = _cyclejs.Rx.Observable.create(function (observer) { + var subscribeEnd = new _cyclejs.Rx.AsyncSubject(); + var onUnsubscribe = _cyclejs.Rx.Disposable.create(function () { + subscribeEnd.onNext(scheduler.now()); + subscribeEnd.onCompleted(); + }); + var p = stream.publish(); + var diagram = diagramStream(p, scheduler, correctedMaxTime); + var finalDiagram = diagram.combineLatest(subscribeEnd, function (diagram, e) { + // eventualEnd is when the stream would have finished had we not unsubscribed + diagram.eventualEnd = diagram.end; + + // end is when the observer unsubscribed (or the stream ended naturally) + diagram.end = e; + return diagram; + }); + + // Give the observer his information + p.subscribe(observer); + + // watch final diagram ourselves + subject.onNext(finalDiagram); + + // start the flow + p.connect(); + + return onUnsubscribe; + }); + + return { + diagrams: diagrams, + stream: newStream + }; } -function getDiagramPromise(stream, scheduler) { - var diagram = {}; - var subject = new _cyclejs.Rx.BehaviorSubject([]); - stream.observeOn(scheduler).timestamp(scheduler).map(function (x) { - if (typeof x.value !== 'object') { - x.value = _immutable2['default'].Map({ - content: x.value, - id: _rxmarblesComponentsSandboxUtils2['default'].calculateNotificationContentHash(x.value) - }); - } - // converts timestamp to % of MAX_VT_TIME - return x.value.set('time', x.timestamp / MAX_VT_TIME * 100); - }).reduce(function (acc, x) { - acc.push(x); - return acc; - }, []).subscribe(function onNext(x) { - diagram.notifications = x; - subject.onNext(diagram); - }, function onError(e) { - console.warn('Error in the diagram promise stream: ' + e); - }, function onComplete() { - diagram.end = scheduler.now(); +function getObservedStreams(diagrams, scheduler, correctedMaxTime) { + var observedStreams = diagrams.get('diagrams').map(function (diagram) { + return toVTStream(diagram, scheduler); + }).map(function (s) { + return observeUsage(s, scheduler, correctedMaxTime); + }); + var inputStreams = observedStreams.map(function (s) { + return s.stream; + }); + // merge all the diagram streams such that we can keep a FIFO order on the final diagrams + var observedInputDiagramStream = _cyclejs.Rx.Observable.merge(observedStreams.map(function (s) { + return s.diagrams; + })).flatMap(function (d$, i) { + return d$.map(function (diag) { + return { diag: diag, i: i }; + }); + }).toArray().map(function (results) { + return results.sort(function (a, b) { + return a.i - b.i; + }).map(function (r) { + return r.diag; + }); + }).publishLast(); + observedInputDiagramStream.connect(); + var observedInputDiagrams = observedInputDiagramStream.startWith([]); + + return { inputStreams: inputStreams, observedInputDiagrams: observedInputDiagrams }; +} + +function diagramStream(stream, scheduler, correctedMaxTime) { + return _cyclejs.Rx.Observable.defer(function () { + var diagram = { start: scheduler.now() }; + return stream.observeOn(scheduler).timestamp(scheduler).takeUntilWithTime(new Date(correctedMaxTime), scheduler).map(function (x) { + if (typeof x.value !== 'object') { + x.value = _immutable2['default'].Map({ + content: x.value, + id: _rxmarblesComponentsSandboxUtils2['default'].calculateNotificationContentHash(x.value) + }); + } + // converts timestamp to % of MAX_VT_TIME + return x.value.set('time', x.timestamp / MAX_VT_TIME * 100); + })['catch'](function (e) { + console.warn('Error in the diagram promise stream: ' + e); + return _cyclejs.Rx.Observable.empty(); + }).toArray().map(function (notifications) { + diagram.end = scheduler.now(); + diagram.notifications = notifications; + return diagram; + }); }); - return subject.asObservable(); +} + +function getDiagramPromise(stream, scheduler, correctedMaxTime) { + var s = diagramStream(stream, scheduler, correctedMaxTime).publishLast(); + s.connect(); + return s.startWith([]); } function toImmutableDiagramData(diagramData) { - return _immutable2['default'].Map({}).set('notifications', _immutable2['default'].List(diagramData.notifications).map(_immutable2['default'].Map)).set('end', diagramData.end); + return _immutable2['default'].Map({}).set('notifications', _immutable2['default'].List(diagramData.notifications).map(_immutable2['default'].Map)).set('end', diagramData.end).set('start', diagramData.start).set('eventualEnd', diagramData.eventualEnd || diagramData.end); } function getOutputDiagram$(example$, inputDiagrams$) { return inputDiagrams$.withLatestFrom(example$, function (diagrams, example) { var vtscheduler = makeScheduler(); - var inputVTStreams = diagrams.get('diagrams').map(function (diagram) { - return toVTStream(diagram, vtscheduler); - }); - var outputVTStream = example.get('apply')(inputVTStreams, vtscheduler); // Necessary hack to include marbles at exactly 100.01 var correctedMaxTime = MAX_VT_TIME + 0.02; - outputVTStream = outputVTStream.takeUntilWithTime(correctedMaxTime, vtscheduler); + + var _getObservedStreams = getObservedStreams(diagrams, vtscheduler, correctedMaxTime); + + var inputStreams = _getObservedStreams.inputStreams; + var observedInputDiagrams = _getObservedStreams.observedInputDiagrams; + + var outputVTStream = example.get('apply')(inputStreams, vtscheduler); var outputDiagram = getDiagramPromise(outputVTStream, vtscheduler, MAX_VT_TIME); vtscheduler.start(); - return outputDiagram.map(toImmutableDiagramData); + + return outputDiagram.map(toImmutableDiagramData).zip(observedInputDiagrams.map(function (diagrams) { + return diagrams.map(toImmutableDiagramData); + }), function (od, ids) { + return { + outputDiagram: od, + observedInputDiagrams: ids + }; + }); }).mergeAll(); } @@ -21192,7 +32117,12 @@ var Rx = _cyclejs2['default'].Rx; var h = _cyclejs2['default'].h; function renderOperatorLabel(label) { + var small = arguments[1] === undefined ? false : arguments[1]; + var fontSize = label.length >= 45 ? 1.3 : label.length >= 30 ? 1.5 : 2; + if (small) { + fontSize *= 0.5; + } var style = { fontFamily: _rxmarblesStylesFonts2['default'].fontCode, fontWeight: '400', @@ -21202,38 +32132,59 @@ function renderOperatorLabel(label) { } function renderOperator(label) { - var style = _rxmarblesStylesUtils.mergeStyles({ + var small = arguments[1] === undefined ? false : arguments[1]; + + var style = (0, _rxmarblesStylesUtils.mergeStyles)({ border: '1px solid rgba(0,0,0,0.06)', - padding: _rxmarblesStylesDimens2['default'].spaceMedium, + padding: small ? _rxmarblesStylesDimens2['default'].spaceTiny : _rxmarblesStylesDimens2['default'].spaceMedium, textAlign: 'center' }, _rxmarblesStylesUtils.elevation2Style); - return h('div.operatorBox', { style: style }, [_rxmarblesStylesUtils.elevation2Before, renderOperatorLabel(label), _rxmarblesStylesUtils.elevation2After]); + return h('div.operatorBox', { style: style }, [_rxmarblesStylesUtils.elevation2Before, renderOperatorLabel(label, small), _rxmarblesStylesUtils.elevation2After]); +} + +function renderObservedInputs(inputs) { + return inputs.map(function (input, i) { + return h('x-diagram.sandboxObservedInput', { + key: 'observedInput' + i, + data: input, + interactive: false, + compact: true, + ghost: true + }); + }); } function getSandboxStyle(width) { - return _rxmarblesStylesUtils.mergeStyles({ + return (0, _rxmarblesStylesUtils.mergeStyles)({ background: _rxmarblesStylesColors2['default'].white, width: width, borderRadius: '2px' }, _rxmarblesStylesUtils.elevation1Style); } -function renderSandbox(inputDiagrams, operatorLabel, outputDiagram, width) { - return h('div.sandboxRoot', { style: getSandboxStyle(width) }, [inputDiagrams.get('diagrams').map(function (diagram, index) { +function renderSandbox(inputDiagrams, operatorLabel, outputDiagramData, width, showSubscriptions) { + var children = [inputDiagrams.get('diagrams').map(function (diagram, index) { return h('x-diagram.sandboxInputDiagram', { key: 'inputDiagram' + index, data: diagram, - interactive: true + interactive: true, + ghost: false }); }), renderOperator(operatorLabel), h('x-diagram.sandboxOutputDiagram', { key: 'outputDiagram', - data: outputDiagram, + data: outputDiagramData.outputDiagram, interactive: false - })]); + })]; + + if (showSubscriptions) { + children.push(renderOperator('subscription details', true), renderObservedInputs(outputDiagramData.observedInputDiagrams)); + } + + return h('div.sandboxRoot', { style: getSandboxStyle(width) }, children); } function makeInputDiagrams(example) { return _immutable2['default'].Map({ 'diagrams': example.get('inputs').map(_rxmarblesComponentsSandboxSandboxInput.prepareInputDiagram).map(function (diag) { - return _rxmarblesComponentsSandboxSandboxInput.augmentWithExampleKey(diag, example.get('key')); + return (0, _rxmarblesComponentsSandboxSandboxInput.augmentWithExampleKey)(diag, example.get('key')); }) }); } @@ -21280,22 +32231,28 @@ function sandboxComponent(interactions, properties) { return ev.data; }); var width$ = properties.get('width').startWith('100%'); + var showSubscriptions$ = properties.get('showSubscriptions').startWith(true); var example$ = properties.get('route').filter(isTruthy).map(function (key) { return _immutable2['default'].Map(_rxmarblesDataExamples2['default'][key]).set('key', key); }).shareReplay(1); var inputDiagrams$ = example$.map(makeInputDiagrams).map(markAllDiagramsAsFirst).shareReplay(1); //inputDiagrams$ = animateData$(inputDiagrams$); - var newInputDiagrams$ = _rxmarblesComponentsSandboxSandboxInput.makeNewInputDiagramsData$(changeInputDiagram$, inputDiagrams$); + var newInputDiagrams$ = (0, _rxmarblesComponentsSandboxSandboxInput.makeNewInputDiagramsData$)(changeInputDiagram$, inputDiagrams$); //let allInputDiagrams$ = inputDiagrams$.merge(newInputDiagrams$); var operatorLabel$ = example$.map(function (example) { return example.get('label'); }); - var firstOutputDiagram$ = _rxmarblesComponentsSandboxSandboxOutput.getOutputDiagram$(example$, inputDiagrams$).map(markAsFirstDiagram); - var newOutputDiagram$ = _rxmarblesComponentsSandboxSandboxOutput.getOutputDiagram$(example$, newInputDiagrams$); + var firstOutputDiagram$ = (0, _rxmarblesComponentsSandboxSandboxOutput.getOutputDiagram$)(example$, inputDiagrams$).map(function (d) { + return { + outputDiagram: markAsFirstDiagram(d.outputDiagram), + observedInputDiagrams: d.observedInputDiagrams.map(markAsFirstDiagram) + }; + }); + var newOutputDiagram$ = (0, _rxmarblesComponentsSandboxSandboxOutput.getOutputDiagram$)(example$, newInputDiagrams$); var outputDiagram$ = firstOutputDiagram$.merge(newOutputDiagram$); return { - vtree$: Rx.Observable.combineLatest(inputDiagrams$, operatorLabel$, outputDiagram$, width$, renderSandbox) + vtree$: Rx.Observable.combineLatest(inputDiagrams$, operatorLabel$, outputDiagram$, width$, showSubscriptions$, renderSandbox) }; } @@ -21400,7 +32357,7 @@ module.exports = { }, "concat": { - "label": "concat", + "label": "concat(a, b)", "inputs": [[{ t: 0, d: 1 }, { t: 15, d: 1 }, { t: 50, d: 1 }, 57], [{ t: 0, d: 2 }, { t: 8, d: 2 }, 12]], "apply": function apply(inputs) { return Rx.Observable.concat(inputs); @@ -21408,7 +32365,7 @@ module.exports = { }, "merge": { - "label": "merge", + "label": "merge(a, b)", "inputs": [[{ t: 0, d: 20 }, { t: 15, d: 40 }, { t: 30, d: 60 }, { t: 45, d: 80 }, { t: 60, d: 100 }], [{ t: 37, d: 1 }, { t: 68, d: 1 }]], "apply": function apply(inputs) { return Rx.Observable.merge(inputs); @@ -21416,7 +32373,7 @@ module.exports = { }, "sample": { - "label": "sample", + "label": "a.sample(b)", "inputs": [[{ t: 0, d: 1 }, { t: 20, d: 2 }, { t: 40, d: 3 }, { t: 60, d: 4 }, { t: 80, d: 5 }], [{ t: 10, d: "A" }, { t: 25, d: "B" }, { t: 33, d: "C" }, { t: 70, d: "D" }, 90]], "apply": function apply(inputs) { return inputs[0].sample(inputs[1]); @@ -21432,7 +32389,7 @@ module.exports = { }, "withLatestFrom": { - "label": "withLatestFrom((x, y) => \"\" + x + y)", + "label": "xs.withLatestFrom(ys, (x, y) => \"\" + x + y)", "inputs": [[{ t: 0, d: 1 }, { t: 20, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, { t: 92, d: 5 }], [{ t: 10, d: "A" }, { t: 25, d: "B" }, { t: 50, d: "C" }, { t: 57, d: "D" }]], "apply": function apply(inputs) { return inputs[0].withLatestFrom(inputs[1], function (x, y) { @@ -21442,8 +32399,8 @@ module.exports = { }, "zip": { - "label": "zip", - "inputs": [[{ t: 0, d: 1 }, { t: 20, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, { t: 92, d: 5 }], [{ t: 10, d: "A" }, { t: 25, d: "B" }, { t: 50, d: "C" }, { t: 57, d: "D" }]], + "label": "zip(xs, ys, (x, y) => \"\" + x + y)", + "inputs": [[{ t: 0, d: 1 }, { t: 20, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, { t: 92, d: 5 }], [{ t: 10, d: "A" }, { t: 25, d: "B" }, { t: 50, d: "C" }, { t: 57, d: "D" }, 70]], "apply": function apply(inputs) { return Rx.Observable.zip(inputs[0], inputs[1], function (x, y) { return "" + x.get("content") + y.get("content"); @@ -21458,11 +32415,19 @@ var Rx = require("cyclejs").Rx; module.exports = { "amb": { - "label": "amb", + "label": "amb(a, b, c)", "inputs": [[{ t: 10, d: 20 }, { t: 20, d: 40 }, { t: 30, d: 60 }], [{ t: 5, d: 1 }, { t: 15, d: 2 }, { t: 25, d: 3 }], [{ t: 20, d: 0 }, { t: 32, d: 0 }, { t: 44, d: 0 }]], "apply": function apply(inputs) { return Rx.Observable.amb(inputs); } + }, + + "repeat": { + "label": "a.repeat()", + "inputs": [[{ t: 5, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, 35]], + "apply": function apply(inputs) { + return inputs[0].repeat(); + } } }; },{"cyclejs":5}],134:[function(require,module,exports){ @@ -21571,32 +32536,50 @@ module.exports = { }, "pausable": { - "label": "pausable", - "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }]], + "label": "a.publish(p => p.pausable(signal))", + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }, 85], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }, 70]], "apply": function apply(inputs) { - inputs[0].subscribe(function () { - return 0; + var signal = inputs[1].map(function (x) { + return x.get("content"); }); - var subject = new Rx.Subject(); - inputs[1].subscribe(function (x) { - return subject.onNext(x.get("content")); + return inputs[0].publish(function (p) { + return p.pausable(signal); }); - return inputs[0].pausable(subject); + } + }, + + "pausable(cold)": { + "label": "a.pausable(signal)", + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }, 85], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }, 70]], + "apply": function apply(inputs) { + var signal = inputs[1].map(function (x) { + return x.get("content"); + }); + return inputs[0].pausable(signal); } }, "pausableBuffered": { - "label": "pausableBuffered", - "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }]], + "label": "a.publish(p => p.pausableBuffered(signal))", + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }, 85], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }, 70]], "apply": function apply(inputs) { - inputs[0].subscribe(function () { - return 0; + var signal = inputs[1].map(function (x) { + return x.get("content"); }); - var subject = new Rx.Subject(); - inputs[1].subscribe(function (x) { - return subject.onNext(x.get("content")); + return inputs[0].publish(function (p) { + return p.pausableBuffered(signal); }); - return inputs[0].pausableBuffered(subject); + } + }, + + "pausableBuffered(cold)": { + "label": "a.pausableBuffered(signal)", + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }, 85], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }, 70]], + "apply": function apply(inputs) { + var signal = inputs[1].map(function (x) { + return x.get("content"); + }); + return inputs[0].pausableBuffered(signal); } }, @@ -21610,7 +32593,7 @@ module.exports = { "skipLast": { "label": "skipLast(2)", - "inputs": [[{ t: 30, d: 1 }, { t: 40, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }]], + "inputs": [[{ t: 30, d: 1 }, { t: 40, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, 80]], "apply": function apply(inputs) { return inputs[0].skipLast(2); } @@ -21618,7 +32601,7 @@ module.exports = { "skipUntil": { "label": "skipUntil", - "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }], [{ t: 45, d: 0 }, { t: 73, d: 0 }]], + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }], [{ t: 45, d: 0 }, { t: 73, d: 0 }, 80]], "apply": function apply(inputs) { return inputs[0].skipUntil(inputs[1]); } diff --git a/src/app-view.js b/src/app-view.js index 3707785..20f6a45 100644 --- a/src/app-view.js +++ b/src/app-view.js @@ -61,7 +61,7 @@ function vrenderContent(route) { position: 'absolute', top: '0'}, pageRowLastChildStyle)} - ,h('x-sandbox', {key: 'sandbox', route: route, width: '820px'}) + ,h('x-sandbox', {key: 'sandbox', route: route, width: '820px', showSubscriptions: true}) ) ] ); diff --git a/src/components/diagram/diagram-model.js b/src/components/diagram/diagram-model.js index 17a479e..46e1784 100644 --- a/src/components/diagram/diagram-model.js +++ b/src/components/diagram/diagram-model.js @@ -27,8 +27,10 @@ function applyChangeMarbleTime(diagramData, marbleDelta) { } function applyChangeEndTime(diagramData, endDelta) { + var newEnd = diagramData.get('end') + endDelta; return diagramData - .set('end', diagramData.get('end') + endDelta); + .set('end', newEnd) + .set('eventualEnd', newEnd); } function applyMarbleDataConstraints(marbleData) { @@ -46,7 +48,7 @@ function applyEndTimeConstraint(diagramData) { newEndTime = Math.round(newEndTime); newEndTime = Math.min(newEndTime, 100); newEndTime = Math.max(0, newEndTime); - return diagramData.set('end', newEndTime); + return diagramData.set('end', newEndTime).set('eventualEnd', newEndTime); } function applyDiagramDataConstraints(diagramData) { @@ -96,7 +98,9 @@ function diagramModel(properties, intent) { intent.changeEndTime$, properties.get('interactive') ), - isInteractive$: properties.get('interactive').startWith(false) + isInteractive$: properties.get('interactive').startWith(false), + isCompact$: properties.get('compact').startWith(false), + showGhost$: properties.get('ghost').startWith(false) }; } diff --git a/src/components/diagram/diagram-view.js b/src/components/diagram/diagram-view.js index f2b3485..c63c618 100644 --- a/src/components/diagram/diagram-view.js +++ b/src/components/diagram/diagram-view.js @@ -9,98 +9,181 @@ let h = Cycle.h; const MARBLE_WIDTH = 5; // estimate of a marble width, in percentages const diagramSidePadding = Dimens.spaceMedium; -const diagramVerticalMargin = Dimens.spaceLarge; const diagramArrowThickness = '2px'; const diagramArrowSidePadding = Dimens.spaceLarge; const diagramArrowHeadSize = '8px'; const diagramArrowColor = Colors.black; +const diagramArrowColorGhost = Colors.almostWhite; const diagramMarbleSize = Dimens.spaceLarge; const diagramCompletionHeight = '44px'; -const diagramStyle = mergeStyles({ - position: 'relative', - display: 'block', - width: '100%', - height: `calc(${diagramMarbleSize} + 2 * ${diagramVerticalMargin})`, - overflow: 'visible', - cursor: 'default'}, - textUnselectable -); - -const diagramBodyStyle = { - position: 'absolute', - left: `calc(${diagramArrowSidePadding} + ${diagramSidePadding} - + (${diagramMarbleSize} / 2))`, - right: `calc(${diagramArrowSidePadding} + ${diagramSidePadding} - + (${diagramMarbleSize} / 2))`, - top: `calc(${diagramVerticalMargin} + (${diagramMarbleSize} / 2))`, - height: diagramCompletionHeight, - marginTop: `calc(0px - (${diagramCompletionHeight} / 2))` -}; - -function renderMarble(marbleData, isDraggable = false) { - return h('x-marble.diagramMarble', { - key: `marble${marbleData.get('id')}`, - data: marbleData, - isDraggable, - style: {size: diagramMarbleSize} - }); +function diagramVerticalMargin(isCompact) { + return isCompact ? Dimens.spaceSmall : Dimens.spaceLarge; +} + +function diagramStyle(isCompact) { + return mergeStyles({ + position: 'relative', + display: 'block', + width: '100%', + height: `calc(${diagramMarbleSize} + 2 * ${diagramVerticalMargin(isCompact)})`, + overflow: 'visible', + cursor: 'default' + }, + textUnselectable + ); +} + +const paddingToTimeline = `(${diagramArrowSidePadding} + ${diagramSidePadding} + (${diagramMarbleSize} / 2))`; +const timelineSize = `(100% - (2 * ${paddingToTimeline}))`; +function timeLeftPosition(time) { + return `(${paddingToTimeline} + (${timelineSize} * ${time / 100}))`; +} +function timeRightPosition(time) { + return `(${paddingToTimeline} + (${timelineSize} * ${(100 - time) / 100}))`; +} + +function diagramBodyStyle(isCompact) { + return { + position: 'absolute', + left: `calc(${paddingToTimeline})`, + right: `calc(${paddingToTimeline})`, + top: `calc(${diagramVerticalMargin(isCompact)} + (${diagramMarbleSize} / 2))`, + height: diagramCompletionHeight, + marginTop: `calc(0px - (${diagramCompletionHeight} / 2))` + }; +} + +function renderMarble(marbleData, isDraggable, showGhost, isGhost) { + if (!isGhost || showGhost) { + return h('x-marble.diagramMarble', { + key: `marble${marbleData.get('id')}`, + data: marbleData, + isDraggable, + style: {size: diagramMarbleSize}, + isGhost + }); + } } -function renderCompletion(diagramData, isDraggable = false) { - let endTime = diagramData.get('end'); +function renderEndpoints(diagramData, isDraggable, showGhost) { + var endpoints = [ + renderEndpoint(diagramData, 'start', 'diagramStart', false, false), + renderEndpoint(diagramData, 'end', 'diagramCompletion', isDraggable, false) + ]; + + // add the eventualEndpoint if it is past the actual end + if (diagramData.get('eventualEnd') > diagramData.get('end')) { + endpoints.push(renderEndpoint(diagramData, 'eventualEnd', 'diagramEventualEnd', false, showGhost)); + } + + return endpoints; +} + +function renderEndpoint(diagramData, timeName, endpointType, isDraggable, isGhost) { + let endTime = diagramData.get(timeName); + // do not render if the time is not defined, or it was at the end of our simulation (and is not draggable) + if (endTime === undefined || endTime > 100 || (!isDraggable && endTime === 100)) { + return undefined; + } + + let color = isGhost ? diagramArrowColorGhost : diagramArrowColor; + let isTall = diagramData.get('notifications').some(marbleData => - Math.abs(marbleData.get('time') - diagramData.get('end')) <= MARBLE_WIDTH*0.5 + Math.abs(marbleData.get('time') - endTime) <= MARBLE_WIDTH*0.5 ); - return h('x-diagram-completion.diagramCompletion', { - key: 'completion', + return h('x-diagram-completion.' + endpointType, { + key: endpointType, time: endTime, isDraggable, isTall, style: { thickness: diagramArrowThickness, - color: diagramArrowColor, + color: color, height: diagramCompletionHeight } }); } -function renderDiagramArrow() { - return h('div.diagramArrow', {style: { - backgroundColor: diagramArrowColor, +function renderDiagramArrow(data, isCompact, showGhost) { + /* render the line in 3 segments: + * - to the left of 'start' render ghosted + * - render between start & end normal + * - to the right of 'end' render ghosted + */ + const arrowStyle = { height: diagramArrowThickness, position: 'absolute', - top: `calc(${diagramVerticalMargin} + (${diagramMarbleSize} / 2))`, - left: diagramSidePadding, - right: diagramSidePadding - }}); + top: `calc(${diagramVerticalMargin(isCompact)} + (${diagramMarbleSize} / 2))` + }; + let sections = []; + let start = data.get('start'); + let end = data.get('end'); + let middleStart = diagramSidePadding; + let middleEnd = diagramSidePadding; + + if (showGhost) { + sections.push(h('div.diagramArrow', { + style: mergeStyles(arrowStyle, { + backgroundColor: diagramArrowColorGhost, + left: middleStart, + right: `calc(${timeRightPosition(start)})` + }) + })); + middleStart = `calc(${timeLeftPosition(start)})`; + + if (end < 100) { + sections.push(h('div.diagramArrow', { + style: mergeStyles(arrowStyle, { + backgroundColor: diagramArrowColorGhost, + left: `calc(${timeLeftPosition(end)})`, + right: middleEnd + }) + })); + middleEnd = `calc(${timeRightPosition(end)})`; + } + } + + if (!showGhost || (start < end)) { + sections.push(h('div.diagramArrow', { + style: mergeStyles(arrowStyle, { + backgroundColor: diagramArrowColor, + left: middleStart, + right: middleEnd + }) + })); + } + + return sections; } -function renderDiagramArrowHead() { +function renderDiagramArrowHead(data, isCompact, showGhost) { + let end = data.get('end'); + let isGhost = end < 100; + let color = (showGhost && isGhost) ? diagramArrowColorGhost : diagramArrowColor; return h('div.diagramArrowHead', {style: { width: 0, height: 0, borderTop: `${diagramArrowHeadSize} solid transparent`, borderBottom: `${diagramArrowHeadSize} solid transparent`, - borderLeft: `calc(2 * ${diagramArrowHeadSize}) solid ${diagramArrowColor}`, + borderLeft: `calc(2 * ${diagramArrowHeadSize}) solid ${color}`, display: 'inline-block', right: `calc(${diagramSidePadding} - 1px)`, position: 'absolute', - top: `calc(${diagramVerticalMargin} + (${diagramMarbleSize} / 2) + top: `calc(${diagramVerticalMargin(isCompact)} + (${diagramMarbleSize} / 2) - ${diagramArrowHeadSize} + (${diagramArrowThickness} / 2))` }}); } -function renderDiagram(data, isInteractive) { +function renderDiagram(data, isInteractive, isCompact, showGhost) { let marblesVTree = data.get('notifications') - .map(notification => renderMarble(notification, isInteractive)) + .map(notification => renderMarble(notification, isInteractive, showGhost, notification.get('time') > (data.get('end') + 0.01))) .toArray(); // from Immutable.List - let completionVTree = renderCompletion(data, isInteractive); - return h('div', {style: diagramStyle}, [ - renderDiagramArrow(), - renderDiagramArrowHead(), - h('div', {style: diagramBodyStyle}, [completionVTree].concat(marblesVTree)) + return h('div', {style: diagramStyle(isCompact)}, [ + renderDiagramArrow(data, isCompact, showGhost), + renderDiagramArrowHead(data, isCompact, showGhost), + h('div', {style: diagramBodyStyle(isCompact)}, renderEndpoints(data, isInteractive, showGhost).concat(marblesVTree)) ]) } @@ -149,6 +232,8 @@ function diagramView(model) { vtree$: Rx.Observable.combineLatest( animateData$(model.data$).merge(model.newData$), model.isInteractive$, + model.isCompact$, + model.showGhost$, renderDiagram ) }; diff --git a/src/components/marble.js b/src/components/marble.js index 7c6345e..09b7166 100644 --- a/src/components/marble.js +++ b/src/components/marble.js @@ -18,9 +18,9 @@ function createContainerStyle(inputStyle) { }; } -function renderSvg(data, isDraggable, inputStyle, isHighlighted) { +function renderSvg(data, isDraggable, inputStyle, isHighlighted, isGhost) { let POSSIBLE_COLORS = [Colors.blue, Colors.green, Colors.yellow, Colors.red]; - let color = POSSIBLE_COLORS[data.get('id') % POSSIBLE_COLORS.length]; + let color = isGhost ? Colors.almostWhite : POSSIBLE_COLORS[data.get('id') % POSSIBLE_COLORS.length]; return svg('svg.marbleShape', { style: mergeStyles({ overflow: 'visible', @@ -31,7 +31,7 @@ function renderSvg(data, isDraggable, inputStyle, isHighlighted) { [ svg('circle', { style: { - stroke: Colors.black, + stroke: isGhost ? Colors.greyLight : Colors.black, fill: color }, attributes: { @@ -43,21 +43,27 @@ function renderSvg(data, isDraggable, inputStyle, isHighlighted) { ); } -function renderInnerContent(data, inputStyle) { +function renderInnerContent(data, inputStyle, isGhost) { + var style = { + position: 'absolute', + width: '100%', + height: '100%', + top: '0', + margin: '0', + textAlign: 'center', + lineHeight: inputStyle.size + }; + + if (isGhost) { + style['color'] = Colors.greyLight; + } + return h('p.marbleContent', { - style: mergeStyles({ - position: 'absolute', - width: '100%', - height: '100%', - top: '0', - margin: '0', - textAlign: 'center', - lineHeight: inputStyle.size}, - textUnselectable) + style: mergeStyles(style, textUnselectable) }, `${data.get('content')}`); } -function render(data, isDraggable, inputStyle, isHighlighted) { +function render(data, isDraggable, inputStyle, isHighlighted, isGhost) { let draggableContainerStyle = { cursor: 'ew-resize' }; @@ -69,8 +75,8 @@ function render(data, isDraggable, inputStyle, isHighlighted) { isDraggable ? draggableContainerStyle : null), attributes: {'data-marble-id': data.get('id')} },[ - renderSvg(data, isDraggable, inputStyle, isHighlighted), - renderInnerContent(data, inputStyle) + renderSvg(data, isDraggable, inputStyle, isHighlighted, isGhost), + renderInnerContent(data, inputStyle, isGhost) ]); } @@ -79,6 +85,7 @@ function marbleComponent(interactions, properties) { let stopHighlight$ = interactions.get('.marbleRoot', 'mouseleave'); let data$ = properties.get('data'); let isDraggable$ = properties.get('isDraggable').startWith(false); + let isGhost$ = properties.get('isGhost').startWith(false); let style$ = properties.get('style').startWith({}); let isHighlighted$ = Rx.Observable.merge( startHighlight$.map(() => true), @@ -87,7 +94,7 @@ function marbleComponent(interactions, properties) { return { vtree$: Rx.Observable.combineLatest( - data$, isDraggable$, style$, isHighlighted$, render + data$, isDraggable$, style$, isHighlighted$, isGhost$, render ) }; } diff --git a/src/components/sandbox/sandbox-input.js b/src/components/sandbox/sandbox-input.js index 935ffaa..916089c 100644 --- a/src/components/sandbox/sandbox-input.js +++ b/src/components/sandbox/sandbox-input.js @@ -28,11 +28,13 @@ function prepareNotification(input, diagramId) { function prepareInputDiagram(diagram, indexInDiagramArray = 0) { let last = diagram[diagram.length - 1]; - return Immutable.Map({}) + let end = (typeof last === 'number') ? last : 100; + return Immutable.Map({ start: 0 }) .set('notifications', getNotifications(diagram) .map(notification => prepareNotification(notification, indexInDiagramArray)) ) - .set('end', (typeof last === 'number') ? last : 100) + .set('end', end) + .set('eventualEnd', end) .set('id', indexInDiagramArray); } diff --git a/src/components/sandbox/sandbox-output.js b/src/components/sandbox/sandbox-output.js index a69a6f5..2d958c9 100644 --- a/src/components/sandbox/sandbox-output.js +++ b/src/components/sandbox/sandbox-output.js @@ -20,77 +20,155 @@ function makeScheduler() { return scheduler; } -function justIncomplete(item, scheduler) { - return new Rx.AnonymousObservable(observer => - scheduler.schedule(() => { observer.onNext(item); }) - ); -} /** * Creates an (virtual time) Rx.Observable from diagram * data (array of data items). */ function toVTStream(diagramData, scheduler) { - let singleMarbleStreams = diagramData.get('notifications').map(item => - justIncomplete(item, scheduler).delay(item.get('time'), scheduler) - ).toArray(); - // Necessary correction to include marbles at time exactly diagramData.end: - let correctedEndTime = diagramData.get('end') + 0.01; - return Rx.Observable.merge(singleMarbleStreams) - .takeUntilWithTime(correctedEndTime, scheduler) - .publish().refCount(); + return Rx.Observable.create(observer => { + let notifications = diagramData.get('notifications') + .map(item => scheduler.scheduleWithRelative(item.get('time'), () => observer.onNext(item))) + .toArray(); + let completion = scheduler.scheduleWithRelative(diagramData.get('end') + 0.01, () => observer.onCompleted()); + let s = new Rx.CompositeDisposable(notifications); + s.add(completion); + return s; + }); } -function getDiagramPromise(stream, scheduler) { - let diagram = {}; - let subject = new Rx.BehaviorSubject([]); - stream - .observeOn(scheduler) - .timestamp(scheduler) - .map(x => { - if (typeof x.value !== 'object') { - x.value = Immutable.Map({ - content: x.value, - id: Utils.calculateNotificationContentHash(x.value) - }); - } - // converts timestamp to % of MAX_VT_TIME - return x.value.set('time', (x.timestamp / MAX_VT_TIME) * 100); - }) - .reduce((acc, x) => { - acc.push(x); - return acc; - },[]) - .subscribe(function onNext(x) { - diagram.notifications = x; - subject.onNext(diagram); - }, function onError(e) { - console.warn('Error in the diagram promise stream: ' + e); - }, function onComplete() { - diagram.end = scheduler.now(); +/** + * Wraps the observable and collects usage information + * Each time the observable is subscribed, produces a notification stream that shows + * - when the subscription started + * - each notification produced + * - when the subscription ended + * - any remaining notifications that would have occurred had the subscription continued + * @param stream + * @param scheduler + * @param correctedMaxTime + */ +function observeUsage(stream, scheduler, correctedMaxTime) { + let subject = new Rx.Subject(); + let diagrams = subject.takeUntilWithTime(new Date(correctedMaxTime), scheduler); + let newStream = Rx.Observable.create(observer => { + let subscribeEnd = new Rx.AsyncSubject(); + let onUnsubscribe = Rx.Disposable.create(() => { + subscribeEnd.onNext(scheduler.now()); + subscribeEnd.onCompleted(); }); - return subject.asObservable(); + let p = stream.publish(); + let diagram = diagramStream(p, scheduler, correctedMaxTime); + let finalDiagram = diagram.combineLatest(subscribeEnd, (diagram, e) => { + // eventualEnd is when the stream would have finished had we not unsubscribed + diagram.eventualEnd = diagram.end; + + // end is when the observer unsubscribed (or the stream ended naturally) + diagram.end = e; + return diagram; + }); + + // Give the observer his information + p.subscribe(observer); + + // watch final diagram ourselves + subject.onNext(finalDiagram); + + // start the flow + p.connect(); + + return onUnsubscribe; + }); + + return { + diagrams, + stream: newStream + }; +} + +function getObservedStreams(diagrams, scheduler, correctedMaxTime) { + let observedStreams = diagrams.get('diagrams') + .map(diagram => toVTStream(diagram, scheduler)) + .map(s => observeUsage(s, scheduler, correctedMaxTime)); + let inputStreams = observedStreams.map(s => s.stream); + // merge all the diagram streams such that we can keep a FIFO order on the final diagrams + let observedInputDiagramStream = Rx.Observable + .merge(observedStreams.map(s => s.diagrams)) + .flatMap((d$, i) => d$.map(diag => { + return {diag, i}; + })) + .toArray() + .map(results => results.sort((a, b) => a.i - b.i).map(r => r.diag)) + .publishLast(); + observedInputDiagramStream.connect(); + let observedInputDiagrams = observedInputDiagramStream.startWith([]); + + return {inputStreams, observedInputDiagrams}; +} + +function diagramStream(stream, scheduler, correctedMaxTime) { + return Rx.Observable.defer(() => { + let diagram = {start: scheduler.now()}; + return stream + .observeOn(scheduler) + .timestamp(scheduler) + .takeUntilWithTime(new Date(correctedMaxTime), scheduler) + .map(x => { + if (typeof x.value !== 'object') { + x.value = Immutable.Map({ + content: x.value, + id: Utils.calculateNotificationContentHash(x.value) + }); + } + // converts timestamp to % of MAX_VT_TIME + return x.value.set('time', (x.timestamp / MAX_VT_TIME) * 100); + }) + .catch(e => { + console.warn('Error in the diagram promise stream: ' + e); + return Rx.Observable.empty(); + }) + .toArray() + .map(notifications => { + diagram.end = scheduler.now(); + diagram.notifications = notifications; + return diagram; + }); + }); +} + +function getDiagramPromise(stream, scheduler, correctedMaxTime) { + let s = diagramStream(stream, scheduler, correctedMaxTime).publishLast(); + s.connect(); + return s.startWith([]); } function toImmutableDiagramData(diagramData) { return Immutable.Map({}) .set('notifications', Immutable.List(diagramData.notifications).map(Immutable.Map)) - .set('end', diagramData.end); + .set('end', diagramData.end) + .set('start', diagramData.start) + .set('eventualEnd', diagramData.eventualEnd || diagramData.end ); } function getOutputDiagram$(example$, inputDiagrams$) { return inputDiagrams$ .withLatestFrom(example$, (diagrams, example) => { let vtscheduler = makeScheduler(); - let inputVTStreams = diagrams.get('diagrams') - .map(diagram => toVTStream(diagram, vtscheduler)); - let outputVTStream = example.get('apply')(inputVTStreams, vtscheduler); // Necessary hack to include marbles at exactly 100.01 let correctedMaxTime = MAX_VT_TIME + 0.02; - outputVTStream = outputVTStream.takeUntilWithTime(correctedMaxTime, vtscheduler); + let { inputStreams, observedInputDiagrams } = getObservedStreams(diagrams, vtscheduler, correctedMaxTime); + let outputVTStream = example.get('apply')(inputStreams, vtscheduler); let outputDiagram = getDiagramPromise(outputVTStream, vtscheduler, MAX_VT_TIME); vtscheduler.start(); - return outputDiagram.map(toImmutableDiagramData); + + return outputDiagram + .map(toImmutableDiagramData) + .zip(observedInputDiagrams.map(diagrams => diagrams.map(toImmutableDiagramData)), (od, ids) => { + return { + outputDiagram: od, + observedInputDiagrams: ids + }; + }); }) .mergeAll(); } diff --git a/src/components/sandbox/sandbox.js b/src/components/sandbox/sandbox.js index 0f91d86..ed61a21 100644 --- a/src/components/sandbox/sandbox.js +++ b/src/components/sandbox/sandbox.js @@ -13,8 +13,11 @@ import {mergeStyles, elevation1Style, elevation2Style, elevation2Before, elevati let Rx = Cycle.Rx; let h = Cycle.h; -function renderOperatorLabel(label) { +function renderOperatorLabel(label, small = false) { let fontSize = (label.length >= 45) ? 1.3 : (label.length >= 30) ? 1.5 : 2; + if (small) { + fontSize *= 0.5; + } let style = { fontFamily: Fonts.fontCode, fontWeight: '400', @@ -23,20 +26,30 @@ function renderOperatorLabel(label) { return h('span.operatorLabel', {style}, label); } -function renderOperator(label) { +function renderOperator(label, small = false) { let style = mergeStyles({ border: '1px solid rgba(0,0,0,0.06)', - padding: Dimens.spaceMedium, + padding: small ? Dimens.spaceTiny : Dimens.spaceMedium, textAlign: 'center'}, elevation2Style ); return h('div.operatorBox', {style}, [ elevation2Before, - renderOperatorLabel(label), + renderOperatorLabel(label, small), elevation2After ]); } +function renderObservedInputs(inputs) { + return inputs.map((input, i) => h('x-diagram.sandboxObservedInput', { + key: "observedInput" + i, + data: input, + interactive: false, + compact: true, + ghost: true + })); +} + function getSandboxStyle(width) { return mergeStyles({ background: Colors.white, @@ -46,22 +59,30 @@ function getSandboxStyle(width) { ); } -function renderSandbox(inputDiagrams, operatorLabel, outputDiagram, width) { - return h('div.sandboxRoot', {style: getSandboxStyle(width)}, [ +function renderSandbox(inputDiagrams, operatorLabel, outputDiagramData, width, showSubscriptions) { + let children = [ inputDiagrams.get('diagrams').map((diagram, index) => h('x-diagram.sandboxInputDiagram', { key: `inputDiagram${index}`, data: diagram, - interactive: true + interactive: true, + ghost: false }) ), renderOperator(operatorLabel), h('x-diagram.sandboxOutputDiagram', { key: 'outputDiagram', - data: outputDiagram, + data: outputDiagramData.outputDiagram, interactive: false - }) - ]); + })]; + + if (showSubscriptions) { + children.push( + renderOperator("subscription details", true), + renderObservedInputs(outputDiagramData.observedInputDiagrams)); + } + + return h('div.sandboxRoot', {style: getSandboxStyle(width)}, children); } function makeInputDiagrams(example) { @@ -111,6 +132,7 @@ function sandboxComponent(interactions, properties) { let changeInputDiagram$ = interactions.get('.sandboxInputDiagram', 'newdata') .map(ev => ev.data); let width$ = properties.get('width').startWith('100%'); + let showSubscriptions$ = properties.get('showSubscriptions').startWith(true); let example$ = properties.get('route') .filter(isTruthy) .map(key => Immutable.Map(Examples[key]).set('key', key)) @@ -126,13 +148,18 @@ function sandboxComponent(interactions, properties) { //let allInputDiagrams$ = inputDiagrams$.merge(newInputDiagrams$); let operatorLabel$ = example$.map(example => example.get('label')); let firstOutputDiagram$ = getOutputDiagram$(example$, inputDiagrams$) - .map(markAsFirstDiagram); + .map(d => { + return { + outputDiagram: markAsFirstDiagram(d.outputDiagram), + observedInputDiagrams: d.observedInputDiagrams.map(markAsFirstDiagram) + }; + }) let newOutputDiagram$ = getOutputDiagram$(example$, newInputDiagrams$); let outputDiagram$ = firstOutputDiagram$.merge(newOutputDiagram$); return { vtree$: Rx.Observable.combineLatest( - inputDiagrams$, operatorLabel$, outputDiagram$, width$, renderSandbox + inputDiagrams$, operatorLabel$, outputDiagram$, width$, showSubscriptions$, renderSandbox ) }; } diff --git a/src/data/combine-examples.js b/src/data/combine-examples.js index 77d3a58..1f97d24 100644 --- a/src/data/combine-examples.js +++ b/src/data/combine-examples.js @@ -15,7 +15,7 @@ module.exports = { }, "concat": { - "label": "concat", + "label": "concat(a, b)", "inputs": [ [{t:0, d:1}, {t:15, d:1}, {t:50, d:1}, 57], [{t:0, d:2}, {t:8, d:2}, 12] @@ -26,7 +26,7 @@ module.exports = { }, "merge": { - "label": "merge", + "label": "merge(a, b)", "inputs": [ [{t:0, d:20}, {t:15, d:40}, {t:30, d:60}, {t:45, d:80}, {t:60, d:100}], [{t:37, d:1}, {t:68, d:1}] @@ -37,7 +37,7 @@ module.exports = { }, "sample": { - "label": "sample", + "label": "a.sample(b)", "inputs": [ [{t:0, d:1}, {t:20, d:2}, {t:40, d:3}, {t:60, d:4}, {t:80, d:5}], [{t:10, d:"A"}, {t:25, d:"B"}, {t:33, d:"C"}, {t:70, d:"D"}, 90] @@ -58,7 +58,7 @@ module.exports = { }, "withLatestFrom": { - "label": "withLatestFrom((x, y) => \"\" + x + y)", + "label": "xs.withLatestFrom(ys, (x, y) => \"\" + x + y)", "inputs": [ [{t:0, d:1}, {t:20, d:2}, {t:65, d:3}, {t:75, d:4}, {t:92, d:5}], [{t:10, d:"A"}, {t:25, d:"B"}, {t:50, d:"C"}, {t:57, d:"D"}] @@ -71,10 +71,10 @@ module.exports = { }, "zip": { - "label": "zip", + "label": "zip(xs, ys, (x, y) => \"\" + x + y)", "inputs": [ [{t:0, d:1}, {t:20, d:2}, {t:65, d:3}, {t:75, d:4}, {t:92, d:5}], - [{t:10, d:"A"}, {t:25, d:"B"}, {t:50, d:"C"}, {t:57, d:"D"}] + [{t:10, d:"A"}, {t:25, d:"B"}, {t:50, d:"C"}, {t:57, d:"D"}, 70] ], "apply": function(inputs) { return Rx.Observable.zip(inputs[0], inputs[1], diff --git a/src/data/conditional-examples.js b/src/data/conditional-examples.js index 325d321..fee66d9 100644 --- a/src/data/conditional-examples.js +++ b/src/data/conditional-examples.js @@ -2,7 +2,7 @@ var Rx = require('cyclejs').Rx; module.exports = { "amb": { - "label": "amb", + "label": "amb(a, b, c)", "inputs": [ [{t:10, d:20}, {t:20, d:40}, {t:30, d:60}], [{t:5, d:1}, {t:15, d:2}, {t:25, d:3}], @@ -11,5 +11,15 @@ module.exports = { "apply": function(inputs) { return Rx.Observable.amb(inputs); } + }, + + "repeat": { + "label": "a.repeat()", + "inputs": [ + [{t: 5, d: 1}, {t: 10, d: 2}, {t: 20, d: 3}, 35] + ], + "apply": function (inputs) { + return inputs[0].repeat(); + } } }; diff --git a/src/data/filter-examples.js b/src/data/filter-examples.js index f81f0a3..e860ed5 100644 --- a/src/data/filter-examples.js +++ b/src/data/filter-examples.js @@ -72,30 +72,50 @@ module.exports = { }, "pausable": { - "label": "pausable", + "label": "a.publish(p => p.pausable(signal))", "inputs": [ - [{t:0, d:1}, {t:10, d:2}, {t:20, d:3}, {t:30, d:4}, {t:40, d:5}, {t:50, d:6}, {t:60, d:7}, {t:70, d:8}, {t:80, d:9}], - [{t:15, d:true}, {t:35, d:false}, {t:55, d:true}] + [{t:0, d:1}, {t:10, d:2}, {t:20, d:3}, {t:30, d:4}, {t:40, d:5}, {t:50, d:6}, {t:60, d:7}, {t:70, d:8}, {t:80, d:9}, 85], + [{t:15, d:true}, {t:35, d:false}, {t:55, d:true}, 70] + ], + "apply": function(inputs) { + let signal = inputs[1].map(x => x.get('content')); + return inputs[0].publish(p => p.pausable(signal)); + } + }, + + "pausable(cold)": { + "label": "a.pausable(signal)", + "inputs": [ + [{t:0, d:1}, {t:10, d:2}, {t:20, d:3}, {t:30, d:4}, {t:40, d:5}, {t:50, d:6}, {t:60, d:7}, {t:70, d:8}, {t:80, d:9}, 85], + [{t:15, d:true}, {t:35, d:false}, {t:55, d:true}, 70] ], "apply": function(inputs) { - inputs[0].subscribe(() => 0); - var subject = new Rx.Subject(); - inputs[1].subscribe(x => subject.onNext(x.get('content'))); - return inputs[0].pausable(subject); + let signal = inputs[1].map(x => x.get('content')); + return inputs[0].pausable(signal); } }, "pausableBuffered": { - "label": "pausableBuffered", + "label": "a.publish(p => p.pausableBuffered(signal))", "inputs": [ - [{t:0, d:1}, {t:10, d:2}, {t:20, d:3}, {t:30, d:4}, {t:40, d:5}, {t:50, d:6}, {t:60, d:7}, {t:70, d:8}, {t:80, d:9}], - [{t:15, d:true}, {t:35, d:false}, {t:55, d:true}] + [{t:0, d:1}, {t:10, d:2}, {t:20, d:3}, {t:30, d:4}, {t:40, d:5}, {t:50, d:6}, {t:60, d:7}, {t:70, d:8}, {t:80, d:9}, 85], + [{t:15, d:true}, {t:35, d:false}, {t:55, d:true}, 70] ], "apply": function(inputs) { - inputs[0].subscribe(() => 0); - var subject = new Rx.Subject(); - inputs[1].subscribe(x => subject.onNext(x.get('content'))); - return inputs[0].pausableBuffered(subject); + let signal = inputs[1].map(x => x.get('content')); + return inputs[0].publish(p => p.pausableBuffered(signal)); + } + }, + + "pausableBuffered(cold)": { + "label": "a.pausableBuffered(signal)", + "inputs": [ + [{t:0, d:1}, {t:10, d:2}, {t:20, d:3}, {t:30, d:4}, {t:40, d:5}, {t:50, d:6}, {t:60, d:7}, {t:70, d:8}, {t:80, d:9}, 85], + [{t:15, d:true}, {t:35, d:false}, {t:55, d:true}, 70] + ], + "apply": function(inputs) { + let signal = inputs[1].map(x => x.get('content')); + return inputs[0].pausableBuffered(signal); } }, @@ -112,7 +132,7 @@ module.exports = { "skipLast": { "label": "skipLast(2)", "inputs": [ - [{t:30, d:1}, {t:40, d:2}, {t:65, d:3}, {t:75, d:4}] + [{t:30, d:1}, {t:40, d:2}, {t:65, d:3}, {t:75, d:4}, 80 ] ], "apply": function(inputs) { return inputs[0].skipLast(2); @@ -123,7 +143,7 @@ module.exports = { "label": "skipUntil", "inputs": [ [{t:0, d:1}, {t:10, d:2}, {t:20, d:3}, {t:30, d:4}, {t:40, d:5}, {t:50, d:6}, {t:60, d:7}, {t:70, d:8}, {t:80, d:9}], - [{t:45, d:0}, {t:73, d:0}] + [{t:45, d:0}, {t:73, d:0}, 80] ], "apply": function(inputs) { return inputs[0].skipUntil(inputs[1]);