/**
  * Returns a stream that emits whenever an action that should close the menu occurs.
  * @return {?}
  */
 _menuClosingActions() {
     const /** @type {?} */ backdrop = /** @type {?} */ ((this._overlayRef)).backdropClick();
     const /** @type {?} */ detachments = /** @type {?} */ ((this._overlayRef)).detachments();
     const /** @type {?} */ parentClose = this._parentMenu ? this._parentMenu.close : of();
     const /** @type {?} */ hover = this._parentMenu ? this._parentMenu._hovered().pipe(filter(active => active !== this._menuItemInstance), filter(() => this._menuOpen)) : of();
     return merge(backdrop, parentClose, hover, detachments);
 }
示例#2
0
文件: rx-query.js 项目: vinchu/rxdb
        get: function get() {
            var _this2 = this;

            if (!this._$) {
                // use results$ to emit new results
                var res$ = this._results$.pipe(
                // whe run _ensureEqual() on each subscription
                // to ensure it triggers a re-run when subscribing after some time
                mergeMap(function () {
                    var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(results) {
                        var hasChanged;
                        return _regeneratorRuntime.wrap(function _callee5$(_context5) {
                            while (1) {
                                switch (_context5.prev = _context5.next) {
                                    case 0:
                                        _context5.next = 2;
                                        return _this2._ensureEqual();

                                    case 2:
                                        hasChanged = _context5.sent;

                                        if (!hasChanged) {
                                            _context5.next = 7;
                                            break;
                                        }

                                        return _context5.abrupt('return', 'WAITFORNEXTEMIT');

                                    case 7:
                                        return _context5.abrupt('return', results);

                                    case 8:
                                    case 'end':
                                        return _context5.stop();
                                }
                            }
                        }, _callee5, _this2);
                    }));

                    return function (_x2) {
                        return _ref6.apply(this, arguments);
                    };
                }()), filter(function (results) {
                    return results !== 'WAITFORNEXTEMIT';
                })).asObservable();

                // we also subscribe to the changeEvent-stream so it detects changed if it has subscribers
                var changeEvents$ = this.collection.$.pipe(filter(function (cEvent) {
                    return ['INSERT', 'UPDATE', 'REMOVE'].includes(cEvent.data.op);
                }), filter(function () {
                    _this2._ensureEqual();
                    return false;
                }));

                this._$ = merge(res$, changeEvents$);
            }
            return this._$;
        }
 /**
  * Subscribes to changes in drawer mode so we can run change detection.
  * @param {?} drawer
  * @return {?}
  */
 _watchDrawerMode(drawer) {
     if (drawer) {
         drawer._modeChanged.pipe(takeUntil(merge(this._drawers.changes, this._destroyed)))
             .subscribe(() => {
             this._updateContentMargins();
             this._changeDetectorRef.markForCheck();
         });
     }
 }
示例#4
0
export default function setupFLIP(start$, ready$, fadeIn$, options) {
  const other$ = start$.pipe(filter(({ flipType }) => !FLIP_TYPES.includes(flipType)));

  return merge(
    setupFLIPTitle(start$, ready$, fadeIn$, options),
    setupFLIPProject(start$, ready$, fadeIn$, options),
    other$,
  );
}
示例#5
0
文件: execute.js 项目: jdetle/nteract
export function createExecuteCellStream(
  action$: ActionsObservable<*>,
  store: any,
  message: ExecuteRequest,
  id: string
) {
  const state = store.getState();

  const kernel = state.app.kernel;
  const channels = kernel ? kernel.channels : null;

  const kernelConnected =
    kernel &&
    channels &&
    !(kernel.status === "starting" || kernel.status === "not connected");

  if (!kernelConnected) {
    return of({
      type: ERROR_EXECUTING,
      payload: "Kernel not connected!",
      error: true
    });
  }

  const cellStream = executeCellStream(channels, id, message).pipe(
    takeUntil(
      merge(
        action$.pipe(
          filter(laterAction => laterAction.id === id),
          ofType(ABORT_EXECUTION, REMOVE_CELL)
        ),
        action$.pipe(ofType(LAUNCH_KERNEL, LAUNCH_KERNEL_BY_NAME, KILL_KERNEL))
      )
    )
  );

  return merge(
    // We make sure to propagate back to "ourselves" the actual message
    // that we sent to the kernel with the sendExecuteMessage action
    of(sendExecuteMessage(id, message)),
    // Merging it in with the actual stream
    cellStream
  );
}
export const combineEpics = (...epics) => (...args) =>
  merge(
    ...epics.map(epic => {
      const output$ = epic(...args);
      if (!output$) {
        throw new TypeError(`combineEpics: one of the provided Epics "${epic.name || '<anonymous>'}" does not return a stream. Double check you\'re not missing a return statement!`);
      }
      return output$;
    })
  );
 /**
  * @param {?} panel
  * @param {?} _element
  * @param {?} _focusMonitor
  * @param {?} _changeDetectorRef
  */
 constructor(panel, _element, _focusMonitor, _changeDetectorRef) {
     this.panel = panel;
     this._element = _element;
     this._focusMonitor = _focusMonitor;
     this._changeDetectorRef = _changeDetectorRef;
     this._parentChangeSubscription = Subscription.EMPTY;
     // Since the toggle state depends on an @Input on the panel, we
     // need to  subscribe and trigger change detection manually.
     this._parentChangeSubscription = merge(panel.opened, panel.closed, panel._inputChanges.pipe(filter(changes => !!(changes["hideToggle"] || changes["disabled"]))))
         .subscribe(() => this._changeDetectorRef.markForCheck());
     _focusMonitor.monitor(_element.nativeElement);
 }
示例#8
0
export const getObservableFromArray = (app) => (ref: RefOverloadingType) => {
  const arrayRef = getRef(app, ref);
  const streams = ARRAY_EVENTS.map(event =>
    fromEvent(
      arrayRef,
      event,
      data => ({ data, event })
    )
  );

  return merge(...streams);
};
 switchMap(() => {
   const frameReady = new Subject();
   const frameTests = createTestFramer(document, getState, frameReady);
   const challengeResults = frameReady.pipe(
     pluck('checkChallengePayload'),
     map(checkChallengePayload => ({
       checkChallengePayload,
       tests: challengeTestsSelector(getState())
     })),
     switchMap(({ checkChallengePayload, tests }) => {
       const postTests = of(
         updateConsole('// tests completed'),
         checkChallenge(checkChallengePayload)
       ).pipe(delay(250));
       return runTestsInTestFrame(document, tests).pipe(
         switchMap(tests => {
           return from(tests).pipe(
             map(({ message }) => message),
             filter(overEvery(isString, Boolean)),
             map(updateConsole),
             concat(of(updateTests(tests)))
           );
         }),
         concat(postTests)
       );
     })
   );
   const buildAndFrameChallenge = action$.pipe(
     ofType(types.executeChallenge),
     debounceTime(executeDebounceTimeout),
     filter(() => isJSEnabledSelector(getState())),
     switchMap(() => {
       const state = getState();
       const { challengeType } = challengeMetaSelector(state);
       if (challengeType === backend) {
         return buildBackendChallenge(state).pipe(
           tap(frameTests),
           ignoreElements(),
           startWith(initConsole('// running test')),
           catchError(err => of(disableJSOnError(err)))
         );
       }
       return buildFromFiles(state, false).pipe(
         tap(frameTests),
         ignoreElements(),
         startWith(initConsole('// running test')),
         catchError(err => of(disableJSOnError(err)))
       );
     })
   );
   return merge(buildAndFrameChallenge, challengeResults);
 })
示例#10
0
 MatTooltip.prototype._createTooltip = /**
  * Create the tooltip to display
  * @return {?}
  */
 function () {
     var _this = this;
     var /** @type {?} */ overlayRef = this._createOverlay();
     var /** @type {?} */ portal = new ComponentPortal(TooltipComponent, this._viewContainerRef);
     this._tooltipInstance = overlayRef.attach(portal).instance;
     // Dispose of the tooltip when the overlay is detached.
     merge(/** @type {?} */ ((this._tooltipInstance)).afterHidden(), overlayRef.detachments()).subscribe(function () {
         // Check first if the tooltip has already been removed through this components destroy.
         if (_this._tooltipInstance) {
             _this._disposeTooltip();
         }
     });
 };
示例#11
0
export function commActionObservable({ kernel }: NewKernelAction) {
  const commOpenAction$ = kernel.channels.pipe(
    ofMessageType("comm_open"),
    map(commOpenAction)
  );

  const commMessageAction$ = kernel.channels.pipe(
    ofMessageType("comm_msg"),
    map(commMessageAction)
  );

  return merge(commOpenAction$, commMessageAction$).pipe(retry());
}
示例#12
0
 /**
  * @param {?} _intl
  * @param {?} changeDetectorRef
  * @param {?} _sort
  * @param {?} _cdkColumnDef
  */
 constructor(_intl, changeDetectorRef, _sort, _cdkColumnDef) {
     this._intl = _intl;
     this._sort = _sort;
     this._cdkColumnDef = _cdkColumnDef;
     /**
      * Sets the position of the arrow that displays when sorted.
      */
     this.arrowPosition = 'after';
     if (!_sort) {
         throw getSortHeaderNotContainedWithinSortError();
     }
     this._rerenderSubscription = merge(_sort.sortChange, _intl.changes).subscribe(() => {
         changeDetectorRef.markForCheck();
     });
 }
示例#13
0
function DeviceEvents(videoElement) {
  const isVisible = visibilityChange()
    .filter((x) => x === false);

  const isHidden = visibilityChange()
    .debounceTime(INACTIVITY_DELAY)
    .filter((x) => x === true);

  const inBackground = merge(isVisible, isHidden)
    .startWith(false);

  const videoWidth = merge(
    interval(20000),
    videoSizeChange().debounceTime(500)
  )
    .startWith("init")
    .map(() => videoElement.clientWidth * pixelRatio)
    .distinctUntilChanged();

  return {
    videoWidth,
    inBackground,
  };
}
示例#14
0
 get: /**
  * Stream of clicks outside of the autocomplete panel.
  * @return {?}
  */
 function () {
     var _this = this;
     if (!this._document) {
         return of(null);
     }
     return merge(fromEvent(this._document, 'click'), fromEvent(this._document, 'touchend'))
         .pipe(filter(function (event) {
         var /** @type {?} */ clickTarget = /** @type {?} */ (event.target);
         var /** @type {?} */ formField = _this._formField ?
             _this._formField._elementRef.nativeElement : null;
         return _this._panelOpen &&
             clickTarget !== _this._element.nativeElement &&
             (!formField || !formField.contains(clickTarget)) &&
             (!!_this._overlayRef && !_this._overlayRef.overlayElement.contains(clickTarget));
     }));
 },
示例#15
0
文件: execute.js 项目: jdetle/nteract
export function executeCellStream(
  channels: Channels,
  id: string,
  message: ExecuteRequest
) {
  if (!channels || !channels.pipe) {
    return _throw(new Error("kernel not connected"));
  }

  const executeRequest = message;

  // All the streams intended for all frontends
  const cellMessages = channels.pipe(childOf(executeRequest));

  // All the payload streams, intended for one user
  const payloadStream = cellMessages.pipe(payloads());

  const cellAction$ = merge(
    payloadStream.pipe(map(payload => acceptPayloadMessage(id, payload))),

    // All actions for updating cell status
    cellMessages.pipe(
      kernelStatuses(),
      map(status => updateCellStatus(id, status))
    ),

    // Update the input numbering: `[ ]`
    cellMessages.pipe(
      executionCounts(),
      map(ct => updateCellExecutionCount(id, ct))
    ),

    // All actions for new outputs
    cellMessages.pipe(outputs(), map(output => appendOutput(id, output))),

    // clear_output display message
    cellMessages.pipe(ofMessageType("clear_output"), mapTo(clearOutputs(id)))
  );

  // On subscription, send the message
  return Observable.create(observer => {
    const subscription = cellAction$.subscribe(observer);
    channels.next(executeRequest);
    return subscription;
  });
}
示例#16
0
 /**
  * Subscribes to drawer events in order to set a class on the main container element when the
  * drawer is open and the backdrop is visible. This ensures any overflow on the container element
  * is properly hidden.
  * @param {?} drawer
  * @return {?}
  */
 _watchDrawerToggle(drawer) {
     RxChain.from(drawer._animationStarted)
         .call(takeUntil, this._drawers.changes)
         .call(filter, (event) => event.fromState !== event.toState)
         .subscribe((event) => {
         // Set the transition class on the container so that the animations occur. This should not
         // be set initially because animations should only be triggered via a change in state.
         if (event.toState !== 'open-instant') {
             this._renderer.addClass(this._element.nativeElement, 'mat-drawer-transition');
         }
         this._updateContentMargins();
         this._changeDetectorRef.markForCheck();
     });
     if (drawer.mode !== 'side') {
         takeUntil.call(merge(drawer.onOpen, drawer.onClose), this._drawers.changes).subscribe(() => this._setContainerClass(drawer.opened));
     }
 }
示例#17
0
        mergeMap(data => {
          const session = uuid();
          const kernel = Object.assign({}, data.response, {
            channel: kernels.connect(config, data.response.id, session)
          });

          kernel.channel.next(kernelInfoRequest());

          return merge(
            of(
              actions.activateKernelFulfilled({
                serverId,
                kernelName,
                kernel
              })
            )
          );
        })
示例#18
0
    $onInit() {
        const cacheID$ = this.$uiRouter.globals.params$.pluck('cacheID').publishReplay(1).refCount();

        this.shortCaches$ = this.ConfigureState.state$.let(this.ConfigSelectors.selectCurrentShortCaches);
        this.shortModels$ = this.ConfigureState.state$.let(this.ConfigSelectors.selectCurrentShortModels);
        this.shortIGFSs$ = this.ConfigureState.state$.let(this.ConfigSelectors.selectCurrentShortIGFSs);
        this.originalCache$ = cacheID$.distinctUntilChanged().switchMap((id) => {
            return this.ConfigureState.state$.let(this.ConfigSelectors.selectCacheToEdit(id));
        });

        this.isNew$ = cacheID$.map((id) => id === 'new');
        this.itemEditTitle$ = combineLatest(this.isNew$, this.originalCache$, (isNew, cache) => {
            return `${isNew ? 'Create' : 'Edit'} cache ${!isNew && cache.name ? `‘${cache.name}’` : ''}`;
        });
        this.selectionManager = this.configSelectionManager({
            itemID$: cacheID$,
            selectedItemRows$: this.selectedRows$,
            visibleRows$: this.visibleRows$,
            loadedItems$: this.shortCaches$
        });

        this.subscription = merge(
            this.originalCache$,
            this.selectionManager.editGoes$.do((id) => this.edit(id)),
            this.selectionManager.editLeaves$.do((options) => this.$state.go('base.configuration.edit.advanced.caches', null, options))
        ).subscribe();

        this.isBlocked$ = cacheID$;

        this.tableActions$ = this.selectionManager.selectedItemIDs$.map((selectedItems) => [
            {
                action: 'Clone',
                click: () => this.clone(selectedItems),
                available: false
            },
            {
                action: 'Delete',
                click: () => {
                    this.remove(selectedItems);
                },
                available: true
            }
        ]);
    }
 switchMap(() => {
   const proxyLogger = new Subject();
   const frameMain = createMainFramer(document, getState, proxyLogger);
   const buildAndFrameMain = actions.pipe(
     ofType(
       types.updateFile,
       types.executeChallenge,
       types.challengeMounted
     ),
     debounceTime(executeDebounceTimeout),
     switchMap(() =>
       buildFromFiles(getState(), true).pipe(
         map(frameMain),
         ignoreElements(),
         catchError(err => of(disableJSOnError(err)))
       )
     )
   );
   return merge(buildAndFrameMain, proxyLogger.map(updateConsole));
 })
示例#20
0
 MatAutocompleteTrigger.prototype._subscribeToClosingActions = /**
  * This method listens to a stream of panel closing actions and resets the
  * stream every time the option list changes.
  * @return {?}
  */
 function () {
     var _this = this;
     var /** @type {?} */ firstStable = this._zone.onStable.asObservable().pipe(first());
     var /** @type {?} */ optionChanges = this.autocomplete.options.changes.pipe(tap(function () { return _this._positionStrategy.recalculateLastPosition(); }), 
     // Defer emitting to the stream until the next tick, because changing
     // bindings in here will cause "changed after checked" errors.
     delay(0));
     // When the zone is stable initially, and when the option list changes...
     return merge(firstStable, optionChanges)
         .pipe(
     // create a new stream of panelClosingActions, replacing any previous streams
     // that were created, and flatten it so our stream only emits closing events...
     switchMap(function () {
         _this._resetActiveItem();
         _this.autocomplete._setVisibility();
         return _this.panelClosingActions;
     }), 
     // when the first closing event occurs...
     first())
         .subscribe(function (event) { return _this._setValueAndClose(event); });
 };
示例#21
0
  return function rootEpic(...args) {
    const toMerge = epics
      .map(epic => epic(...args));

    return merge$(...toMerge);
  };
示例#22
0
 this._change = platform.isBrowser ? ngZone.runOutsideAngular(() => {
     return merge(fromEvent(window, 'resize'), fromEvent(window, 'orientationchange'));
 }) : of();
示例#23
0
export function createMainChannelFromSockets(
  sockets: {
    [string]: moduleJMP.Socket
  },
  header: HEADER_FILLER = {
    session: uuid(),
    username: getUsername()
  },
  jmp = moduleJMP
) {
  // The mega subject that encapsulates all the sockets as one multiplexed stream
  const subject = Subject.create(
    // $FlowFixMe: figure out if this is a shortcoming in the flow def or our declaration
    Subscriber.create(
      message => {
        // There's always a chance that a bad message is sent, we'll ignore it
        // instead of consuming it
        if (!message || !message.channel) {
          console.warn("message sent without a channel", message);
          return;
        }
        const socket = sockets[message.channel];
        if (!socket) {
          // If, for some reason, a message is sent on a channel we don't have
          // a socket for, warn about it but don't bomb the stream
          console.warn("channel not understood for message", message);
          return;
        }
        const jMessage = new jmp.Message({
          // Fold in the setup header to ease usage of messages on channels
          header: { ...message.header, ...header },
          parent_header: message.parent_header,
          content: message.content,
          metadata: message.metadata,
          buffers: message.buffers
        });
        socket.send(jMessage);
      },
      undefined, // not bothering with sending errors on
      () =>
        // When the subject is completed / disposed, close all the event
        // listeners and shutdown the socket
        Object.keys(sockets).forEach(name => {
          const socket = sockets[name];
          socket.removeAllListeners();
          socket.close();
        })
    ),
    // Messages from kernel on the sockets
    merge(
      // Form an Observable with each socket
      ...Object.keys(sockets).map(name => {
        const socket = sockets[name];

        return fromEvent(socket, "message").pipe(
          map(body => {
            // Route the message for the frontend by setting the channel
            const msg = { ...body, channel: name };
            // Conform to same message format as notebook websockets
            // See https://github.com/n-riesco/jmp/issues/10
            delete msg.idents;
            return msg;
          }),
          publish(),
          refCount()
        );
      })
    ).pipe(publish(), refCount())
  );

  return subject;
}
 return this.items.changes.pipe(startWith(this.items), switchMap(items => merge(...items.map(item => item._hovered))));
示例#25
0
    $onInit() {
        /** @type {Subject<Array<ig.config.model.ShortDomainModel>>} */
        this.visibleRows$ = new Subject();

        /** @type {Subject<Array<ig.config.model.ShortDomainModel>>} */
        this.selectedRows$ = new Subject();

        /** @type {Array<uiGrid.IColumnDefOf<ig.config.model.ShortDomainModel>>} */
        this.columnDefs = [
            {
                name: 'hasIndex',
                displayName: 'Indexed',
                field: 'hasIndex',
                type: 'boolean',
                enableFiltering: true,
                visible: true,
                multiselectFilterOptions: [{value: true, label: 'Yes'}, {value: false, label: 'No'}],
                width: 100,
                cellTemplate: hasIndexTemplate
            },
            {
                name: 'keyType',
                displayName: 'Key type',
                field: 'keyType',
                enableHiding: false,
                filter: {
                    placeholder: 'Filter by key type…'
                },
                cellTemplate: keyCellTemplate,
                minWidth: 165
            },
            {
                name: 'valueType',
                displayName: 'Value type',
                field: 'valueType',
                enableHiding: false,
                filter: {
                    placeholder: 'Filter by value type…'
                },
                sort: {direction: 'asc', priority: 0},
                cellTemplate: valueCellTemplate,
                minWidth: 165
            }
        ];

        /** @type {Observable<string>} */
        this.itemID$ = this.$uiRouter.globals.params$.pluck('modelID');

        /** @type {Observable<Array<ig.config.model.ShortDomainModel>>} */
        this.shortItems$ = this.ConfigureState.state$.let(this.ConfigSelectors.selectCurrentShortModels)
            .do((shortModels = []) => {
                const value = shortModels.every((m) => m.hasIndex);
                this.columnDefs[0].visible = !value;
            })
            .publishReplay(1)
            .refCount();

        this.shortCaches$ = this.ConfigureState.state$.let(this.ConfigSelectors.selectCurrentShortCaches);

        /** @type {Observable<ig.config.model.DomainModel>} */
        this.originalItem$ = this.itemID$.distinctUntilChanged().switchMap((id) => {
            return this.ConfigureState.state$.let(this.ConfigSelectors.selectModelToEdit(id));
        }).distinctUntilChanged().publishReplay(1).refCount();

        this.isNew$ = this.itemID$.map((id) => id === 'new');

        this.itemEditTitle$ = combineLatest(this.isNew$, this.originalItem$, (isNew, item) => {
            return `${isNew ? 'Create' : 'Edit'} model ${!isNew && get(item, 'valueType') ? `‘${get(item, 'valueType')}’` : ''}`;
        });

        this.selectionManager = this.configSelectionManager({
            itemID$: this.itemID$,
            selectedItemRows$: this.selectedRows$,
            visibleRows$: this.visibleRows$,
            loadedItems$: this.shortItems$
        });

        this.tableActions$ = this.selectionManager.selectedItemIDs$.map((selectedItems) => [
            {
                action: 'Clone',
                click: () => this.clone(selectedItems),
                available: false
            },
            {
                action: 'Delete',
                click: () => {
                    this.remove(selectedItems);
                },
                available: true
            }
        ]);

        this.subscription = merge(
            this.originalItem$,
            this.selectionManager.editGoes$.do((id) => this.edit(id)),
            this.selectionManager.editLeaves$.do((options) => this.$state.go('base.configuration.edit.advanced.models', null, options))
        ).subscribe();
    }
示例#26
0
文件: execute.js 项目: jdetle/nteract
 catchError((err, source) =>
   merge(of({ type: ERROR_EXECUTING, payload: err, error: true }), source)
示例#27
0
 get: /**
  * A stream of actions that should close the autocomplete panel, including
  * when an option is selected, on blur, and when TAB is pressed.
  * @return {?}
  */
 function () {
     return merge(this.optionSelections, this.autocomplete._keyManager.tabOut, this._escapeEventStream, this._outsideClickStream);
 },