rxjs/operators#ignoreElements TypeScript Examples

The following examples show how to use rxjs/operators#ignoreElements. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: clipboard.ts    From ble with Apache License 2.0 6 votes vote down vote up
copy: Epic = (action$, { store }) => {
	return fromEvent<ClipboardEvent>(window, 'copy').pipe(
		filter(() => store.editor.selection.size > 0),
		tap(() => {
			store.editor.copy();
		}),
		ignoreElements(),
	);
}
Example #2
Source File: zoom.ts    From ble with Apache License 2.0 6 votes vote down vote up
zoom: Epic = (action$, { store }) => {
	return action$.pipe(
		ofType('zoom'),
		tap(({ factor }) => {
			const scale = store.editor.scale;
			store.editor.setScale(scale * factor);
		}),
		ignoreElements(),
	);
}
Example #3
Source File: timeTravel.ts    From ble with Apache License 2.0 6 votes vote down vote up
redoEpic: Epic = (action$, { store }) => {
	return action$.pipe(
		ofType('redo'),
		filter(() => store.undoManager.canRedo),
		tap(() => {
			store.undoManager.redo();
		}),
		ignoreElements(),
	);
}
Example #4
Source File: timeTravel.ts    From ble with Apache License 2.0 6 votes vote down vote up
undoEpic: Epic = (action$, { store }) => {
	return action$.pipe(
		ofType('undo'),
		filter(() => store.undoManager.canUndo),
		tap(() => {
			store.undoManager.undo();
		}),
		ignoreElements(),
	);
}
Example #5
Source File: select.ts    From ble with Apache License 2.0 6 votes vote down vote up
selectAll: Epic = (action$, { store }) => {
	return fromEvent<KeyboardEvent>(document, 'keydown').pipe(
		filter((ev) => ev.code === 'KeyA' && isShortcut(ev)),
		tap((ev) => {
			ev.preventDefault();
			store.editor.addEntitiesToSelection(store.level.entities);
		}),
		ignoreElements(),
	);
}
Example #6
Source File: select.ts    From ble with Apache License 2.0 6 votes vote down vote up
selectVertex: Epic = (action$, { store }) => {
	return action$.pipe(
		ofType('vertexPointerDown'),
		// middle click is panning only
		filter(({ ev }) => !(ev.data.pointerType === 'mouse' && ev.data.button === 1)),
		filter(() => store.editor.mode === EditorMode.select),
		tap(({ vertexId, ev }) => {
			const point = resolveIdentifier(VertexM, store.level.entities, vertexId);

			if (point === undefined) return;

			if (isShortcut(ev.data.originalEvent)) {
				if (store.editor.vertexSelection.has(point.id)) {
					store.editor.removeVertexFromSelection(point);
				} else {
					store.editor.addVertexToSelection(point);
				}
			} else if (!store.editor.vertexSelection.has(point.id)) {
				store.editor.setVertexSelection([point]);
			}
		}),
		ignoreElements(),
	);
}
Example #7
Source File: select.ts    From ble with Apache License 2.0 6 votes vote down vote up
selectEntity: Epic = (action$, { store }) => {
	return action$.pipe(
		ofType('entityPointerDown'),
		// middle click is panning only
		filter(({ ev }) => !(ev.data.pointerType === 'mouse' && ev.data.button === 1)),
		filter(() => store.editor.mode === EditorMode.select),
		tap(({ entityId, ev }) => {
			// @ts-expect-error
			const entity = resolveIdentifier(EntityM, store.level.entities, entityId);
			if (entity === undefined) return;

			if (isShortcut(ev.data.originalEvent)) {
				if (store.editor.selection.has(entity.id)) {
					store.editor.removeFromSelection(entity);
				} else {
					store.editor.addEntityToSelection(entity);
				}
			} else if (!store.editor.selection.has(entity.id)) {
				store.editor.setSelection([entity]);
			}
		}),
		ignoreElements(),
	);
}
Example #8
Source File: pan.ts    From ble with Apache License 2.0 6 votes vote down vote up
resize: Epic = (action$, { store, app }) => {
	return merge(
		action$.pipe(
			ofType('hydrate'),
		),
		fromEvent(app.renderer, 'resize'),
	).pipe(
		tap(() => {
			const box = app.view.getBoundingClientRect();
			store.editor.setScreenSize(box);
		}),
		ignoreElements(),
	);
}
Example #9
Source File: init.ts    From ble with Apache License 2.0 6 votes vote down vote up
loadLevelFromQueryParam: Epic = (action$, { store }) => {
	const urlParams = new URLSearchParams(window.location.search);
	const levelId = urlParams.get('levelId');

	if (levelId && window.confirm('The saved level will be overwritten. Are you sure?')) {
		return ajax(`https://assets.bombhopper.io/levels/${levelId}.json`).pipe(
			pluck('response'),
			tap((level) => {
				// eslint-disable-next-line @typescript-eslint/no-explicit-any
				const { top, right, bottom, left } = getBounds((level as any).entities);
				const middle = {
					x: left + (right - left) / 2,
					y: top + (bottom - top) / 2,
				};
				applySnapshot(store.level, level);
				store.editor.position.set(middle.x, middle.y);
			}),
			ignoreElements(),
		);
	}

	return EMPTY;
}
Example #10
Source File: delete.ts    From ble with Apache License 2.0 6 votes vote down vote up
backspaceEntityDelete: Epic = (action$, { store, app }) => {
	// it's very important to use app.view here, if document.body was used
	// it would prevent using text fields normally etc
	return fromEvent<KeyboardEvent>(app.view, 'keydown').pipe(
		filter((ev) => ['Backspace', 'Delete'].includes(ev.key)),
		tap((ev) => ev.preventDefault()),
		tap(() => {
			if (store.editor.vertexSelection.size > 0) {
				store.editor.vertexSelection.forEach((vertex: IVertex) => vertex.remove());
			} else {
				store.editor.removeSelected();
			}
			store.editor.setMode(EditorMode.select);
		}),
		ignoreElements(),
	);
}
Example #11
Source File: clipboard.ts    From ble with Apache License 2.0 6 votes vote down vote up
paste: Epic = (action$, { store }) => {
	return fromEvent<ClipboardEvent>(window, 'paste').pipe(
		filter(({ clipboardData }) => !!clipboardData),
		tap(({ clipboardData }) => {
			Array.from(clipboardData?.items || [])
				.filter(({ type }) => type === 'text/plain')
				.forEach((item) => {
					item.getAsString((clipboardContent) => {
						store.editor.paste(clipboardContent);
					});
				});
		}),
		ignoreElements(),
	);
}
Example #12
Source File: clipboard.ts    From ble with Apache License 2.0 6 votes vote down vote up
cut: Epic = (action$, { store }) => {
	return fromEvent<ClipboardEvent>(window, 'cut').pipe(
		filter(() => store.editor.selection.size > 0),
		tap(() => {
			store.editor.cut();
		}),
		ignoreElements(),
	);
}
Example #13
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
dismissNotificationsBannerEpic: EpicSignature = action$ => {
  return action$.pipe(
    filter(isActionOf(Actions.toggleNotificationsBanner)),
    pluck("payload"),
    filter(({ visible }) => !visible),
    tap(({ key }) => StorageModule.handleDismissNotification(key)),
    ignoreElements(),
  );
}
Example #14
Source File: add.ts    From ble with Apache License 2.0 6 votes vote down vote up
addVertex: Epic = (action$, { store }) => {
	return action$.pipe(
		ofType('addVertex'),
		filter(() => store.editor.selection.size === 1),
		tap(({ pos }) => {
			// c'mon Typescript, why do I need this cast -_-
			const selectedEntity = (Array.from(store.editor.selection.values())[0] as IEntity);

			if ('vertices' in selectedEntity.params) {
				selectedEntity.params.addVertex(pos);
				return;
			}
			if (VertexM.is(selectedEntity)) {
				(selectedEntity as IVertex).parentBlock.params.addVertex(pos);
				return;
			}
		}),
		ignoreElements(),
	);
}
Example #15
Source File: BleTransport.ts    From Elastos.Essentials.App with MIT License 6 votes vote down vote up
// TODO we probably will do this at end of open
  async inferMTU() {
    let { mtu } = this.device;
    await this.exchangeAtomicImpl(async () => {
      Logger.log(TAG, "inferMTU exchangeAtomicImpl");
      try {
        mtu =
          (await merge(
            this.notifyObservable.pipe(
              first((buffer) => buffer.readUInt8(0) === 0x08),
              map((buffer) => buffer.readUInt8(5))
            ),
            defer(() => from(this.write(Buffer.from([0x08, 0, 0, 0, 0])))).pipe(
              ignoreElements()
            )
          ).toPromise()) + 3;
      } catch (e: any) {
        Logger.log(TAG, "inferMTU got error:", String(e));
        await bleManager.disconnect(this.id).catch(() => {}); // but we ignore if disconnect worked.

        throw remapError(e);
      }
    });

    if (mtu > 23) {
      const mtuSize = mtu - 3;
      this.mtuSize = mtuSize;
    }

    return this.mtuSize;
  }
Example #16
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
saveAddressEpic: EpicSignature = action$ => {
  return action$.pipe(
    filter(
      isActionOf([Actions.connectLedgerSuccess, Actions.setAddressSuccess]),
    ),
    pluck("payload"),
    tap(payload => {
      let address = "";
      if ("ledgerAddress" in payload) {
        address = payload.ledgerAddress;
      } else {
        address = payload.address;
      }

      StorageModule.setAddress(address);
      StorageModule.updateRecentAddress(address);
    }),
    ignoreElements(),
  );
}
Example #17
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
syncAddressToUrlOnNavigationEpic: EpicSignature = (
  action$,
  state$,
  deps,
) => {
  return action$.pipe(
    filter(isActionOf(Actions.onRouteChange)),
    pluck("payload"),
    tap(() => {
      const { address } = state$.value.ledger.ledger;
      const { transactionsPage } = state$.value.transaction;
      const { locationState } = state$.value.app.app;
      const params = getQueryParamsFromUrl(locationState.search);

      const search =
        transactionsPage > 1
          ? `?address=${address}&page=${transactionsPage}`
          : `?address=${address}`;

      // Update if an address exists, the chart view is active, and
      // if the path search values do not match
      if (
        !!address &&
        onPageWhichIncludesAddressParam(locationState.pathname) &&
        !params.address
      ) {
        deps.router.replace({ search });
      }
    }),
    ignoreElements(),
  );
}
Example #18
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
syncAddressToUrlOnInitializationEpic: EpicSignature = (
  action$,
  state$,
  deps,
) => {
  return action$.pipe(
    filter(isActionOf(Actions.initializeAppSuccess)),
    pluck("payload"),
    pluck("address"),
    tap(() => {
      const { location } = deps.router;
      const { address } = state$.value.ledger.ledger;
      const { transactionsPage } = state$.value.transaction;

      const search =
        transactionsPage > 1
          ? `?address=${address}&page=${transactionsPage}`
          : `?address=${address}`;

      // If the current location does not include the address, sync it
      if (
        onPageWhichIncludesAddressParam(location.pathname) &&
        !location.search.includes(address)
      ) {
        deps.router.replace({ search });
      }
    }),
    ignoreElements(),
  );
}
Example #19
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
searchTransactionNavigationEpic: EpicSignature = (
  action$,
  state$,
  deps,
) => {
  return action$.pipe(
    filter(isActionOf(Actions.searchTransactionByHash)),
    pluck("payload"),
    tap(hash => {
      const { network } = state$.value.ledger.ledger;
      const pathname = `/${network.name.toLowerCase()}/txs/${hash.toLowerCase()}`;
      deps.router.push({ pathname });
    }),
    ignoreElements(),
  );
}
Example #20
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
serializeSettingsStoreEpic: EpicSignature = (action$, state$, deps) => {
  return action$.pipe(
    filter(isActionOf(Actions.updateSetting)),
    tap(() => {
      const settings = state$.value.settings;
      const serializedState = JSON.stringify(settings);
      localStorage.setItem(SETTINGS_STORE_KEY, serializedState);
    }),
    ignoreElements(),
  );
}
Example #21
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
syncTransactionPageEpic: EpicSignature = (action$, state$, deps) => {
  return action$.pipe(
    filter(isActionOf(Actions.setTransactionsPage)),
    pluck("payload"),
    tap(() => {
      const { router } = deps;
      const address = state$.value.ledger.ledger.address;
      const page = state$.value.transaction.transactionsPage;
      router.replace({
        search: `address=${address}&page=${page}`,
      });
    }),
    ignoreElements(),
  );
}
Example #22
Source File: artichoke.ts    From closer-sdk.js with MIT License 6 votes vote down vote up
constructor(
    private artichokeApi: ArtichokeApi,
    private callFactory: CallFactory,
    private roomFactory: RoomFactory,
    private loggerService: LoggerService,
    private heartbeatTimeoutMultiplier: number,
    private fallbackReconnectDelayMs: number,
  ) {
    // Do not move this as a property accessor, it must be only one object to make rx `share` operator work.
    this.connection = merge(
      this.artichokeApi.connection$.pipe(
        filter(serverEvents.OutputHeartbeat.is),
        tap((ev: serverEvents.OutputHeartbeat) => this.handleHeartbeatEvent(ev)),
        ignoreElements(),
      ),
      this.artichokeApi.connection$.pipe(
        filter(serverEvents.Hello.is),
        tap(ev => this.handleHelloEvent(ev)),
      ),
    ).pipe(
      finalize(() => this.handleDisconnect()),
      // On WebSocket error
      retryWhen(errors => this.delayReconnect(errors)),
      takeUntil(this.serverUnreachableEvent),
      // On WebSocket gracefull close
      repeatWhen(attempts => this.delayReconnect(attempts)),
      // IMPORTANT
      // Share the observable, so the internal logic would behave like one consistent stream
      // Without this operator, if client subscribes two times, we would have
      // two heartbeats answers and reconnections logic
      share(),
    );
  }
Example #23
Source File: websocket-client.ts    From closer-sdk.js with MIT License 6 votes vote down vote up
/**
   * Cold observable
   * @param command Message
   */
  public ask(command: roomCommand.SendMessage | roomCommand.SendCustomMessage): Observable<chatEvents.Received> {
    const ref = this.uuidGenerator.next();
    const newCommand = { ...command, ref };

    return merge(
      of(newCommand).pipe(
        tap((cmd: typeof newCommand) => this.send(cmd)),
        ignoreElements(),
      ),
      this.connection$.pipe(
        filter(chatEvents.Received.isReceived),
        filter(rec => rec.ref === ref),
      ),
      this.connection$.pipe(
        filter(errorEvents.Error.isError),
        filter(rec => rec.ref === ref),
        mergeMap(err => throwError(err, undefined)),
      ),
    ).pipe(
      timeout(this.askTimeoutMs),
      take(1),
    );
  }
Example #24
Source File: add.ts    From ble with Apache License 2.0 6 votes vote down vote up
createEntity: Epic = (action$, { store }) => {
	return action$.pipe(
		ofType('createEntity'),
		map(({ pos }) => store.createEntity(pos)),
		filter((entity) => 'vertices' in entity.params),
		tap(() => {
			store.editor.setMode(EditorMode.addVertex);
		}),
		ignoreElements(),
	);
}
Example #25
Source File: pan.ts    From ble with Apache License 2.0 5 votes vote down vote up
globalPan: Epic = (action$, { store, app }) => {
	const [middleClick$, otherClick$] = partition(fromEvent<PointerEvent>(app.view, 'pointerdown'), (ev) => ev.button === 1);

	const startPanning$ = merge(
		middleClick$.pipe(
			tap((ev) => {
				// on Windows middle-click is for multidirectional scroll
				ev.preventDefault();
			}),
		),
		otherClick$.pipe(
			filter((ev) => store.editor.mode === EditorMode.pan || ev.button === 1),
		),
	);

	return startPanning$.pipe(
		tap(() => {
			store.editor.setPanning(true);
		}),
		map(({ clientX, clientY }) => ({ // save starting values
			start: {
				x: clientX,
				y: clientY,
			},
			pivot: {
				x: store.editor.position.x,
				y: store.editor.position.y,
			},
		})),
		switchMap(({ start, pivot }) => {
			const oldMode = store.editor.mode;
			store.editor.setMode(EditorMode.pan);

			return fromEvent<PointerEvent>(document, 'pointermove').pipe(
				tap(({ clientX, clientY }) => {
					const { scale } = store.editor;
					const deltaX = pivot.x + (start.x - clientX) * (1/scale);
					const deltaY = pivot.y + (start.y - clientY) * (1/scale);

					store.editor.position.set(deltaX, deltaY);
				}),
				takeUntil(fromEvent(document, 'pointerup').pipe(
					tap(() => {
						store.editor.setMode(oldMode);
						store.editor.setPanning(false);
					})
				)),
			);
		}),
		ignoreElements(),
	);
}
Example #26
Source File: select.ts    From ble with Apache License 2.0 5 votes vote down vote up
entityMove: Epic = (action$, { store }) => {
	return action$.pipe (
		ofType('entityPointerDown'),
		filter(() => store.editor.mode === EditorMode.select),
		// middle click is panning only
		filter(({ ev }) => !(ev.data.pointerType === 'mouse' && ev.data.button === 1)),
		// it's important to use global and not original event
		// because TouchEvents don't have clientX
		pluck('ev', 'data', 'global'),
		// we copy the relevant data because react pools events
		map(({ x, y }) => ({
			x: x + store.editor.renderZone.x,
			y: y + store.editor.renderZone.y,
		})),
		tap(() => {
			store.undoManager.startGroup();
		}),
		switchMap(({ x, y }) => fromEvent<PointerEvent>(document, 'pointermove').pipe(
			map(({ clientX, clientY }) => new Vector(clientX, clientY)),
			startWith(new Vector(x, y)),
			pairwise(),
			map(([prev, curr]) => curr.clone().sub(prev)),
			filter((vec) => vec.len2() !== 0),
			map((vec) => vec.scale(1/store.editor.scale)),
			scan((acc, delta) => {
				const totalDelta = acc.clone().add(delta);

				const displacement = snapBoxToGrid(
					new Box(
						store.editor.selectionAsAabb.pos.clone().add(totalDelta),
						store.editor.selectionAsAabb.w,
						store.editor.selectionAsAabb.h,
					),
					store.editor.gridCellSize,
				);

				store.editor.selection.forEach((entity: IEntity) => {
					entity.params.move(totalDelta.x + displacement.x, totalDelta.y + displacement.y);
				});

				return displacement.reverse();
			}, new Vector(0, 0)),
			takeUntil(fromEvent(document, 'pointerup').pipe(
				tap(() => {
					store.undoManager.stopGroup();
				}),
			)),
		)),
		ignoreElements(),
	);
}
Example #27
Source File: select.ts    From ble with Apache License 2.0 5 votes vote down vote up
pointMove: Epic = (action$, { store }) => {
	return action$.pipe (
		ofType('vertexPointerDown'),
		// middle click is panning only
		filter(({ ev }) => !(ev.data.pointerType === 'mouse' && ev.data.button === 1)),
		filter(() => store.editor.mode === EditorMode.select),
		mergeMap(({ vertexId }) => {
			const storePoint = resolveIdentifier(VertexM, store.level.entities, vertexId);
			if (storePoint === undefined) return empty();

			return of({
				storePoint,
			});
		}),
		tap(() => {
			store.undoManager.startGroup();
		}),
		switchMap(({ storePoint }) => fromEvent<PointerEvent>(document, 'pointermove').pipe(
			tap((ev) => {
				const pos = {
					x: ev.clientX - store.editor.renderZone.x,
					y: ev.clientY - store.editor.renderZone.y,
				};

				const posInWorld = store.editor.screenToWorld(pos);
				const snappedPos = snapToGrid(posInWorld, store.editor.gridCellSize);

				const delta = {
					x: snappedPos.x - storePoint.x,
					y: snappedPos.y - storePoint.y,
				};
				// we move the point under the cursor, snapping it to the grid
				storePoint.set(snappedPos.x, snappedPos.y);

				// the other seleced vertices aren't snapped
				store.editor.vertexSelection.forEach((vertex: IVertex) => {
					if (vertex === storePoint) return;

					vertex.move(delta.x, delta.y);
				});
			}),
			takeUntil(fromEvent(document, 'pointerup').pipe(
				tap(() => {
					store.undoManager.stopGroup();
					storePoint.parentBlock.params.cleanSuperposedVertices();
				}),
			)),
		)),
		ignoreElements(),
	);
}
Example #28
Source File: epics.ts    From anthem with Apache License 2.0 5 votes vote down vote up
clearAllRecentAddressesEpic: EpicSignature = action$ => {
  return action$.pipe(
    filter(isActionOf(Actions.clearAllRecentAddresses)),
    tap(StorageModule.clearRecentAddresses),
    ignoreElements(),
  );
}
Example #29
Source File: select.ts    From ble with Apache License 2.0 5 votes vote down vote up
selectionBox: Epic = (action$, { store }) => {
	return action$.pipe(
		ofType('backgroundPointerDown'),
		// middle click is panning only
		filter(({ ev }) => !(ev.data.pointerType === 'mouse' && ev.data.button === 1)),
		filter(() => store.editor.mode === EditorMode.select),
		// it's important to use global and not original event
		// because TouchEvents don't have clientX
		pluck('ev', 'data', 'global'),
		map((global) => store.editor.screenToWorld(global)),
		tap((worldPos) => {
			store.editor.startSelectionBox(worldPos);
		}),
		switchMapTo(fromEvent<PointerEvent>(document, 'pointermove').pipe(
			map((ev) => store.editor.screenToWorld({
				x: ev.clientX - store.editor.renderZone.x,
				y: ev.clientY - store.editor.renderZone.y,
			})),
			tap((posInWorld) => {
				store.editor.updateSelectionBox(posInWorld);
			}),
			takeUntil(merge(
				fromEvent<PointerEvent>(document, 'pointerup').pipe(
					map((ev) => isShortcut(ev)),
				),
				fromMobx(() => store.editor.mode).pipe(
					filter((mode) => mode !== EditorMode.select),
					mapTo(false),
				),
			).pipe(
				tap((shortcut) => {
					const entitiesToAdd = store.level.entities.filter((entity: IEntity) => {
						if ('params' in entity && 'asSatCircle' in entity.params) {
							const tester = store.editor.selectionBoxAsSat instanceof Vector ? pointInCircle : testPolygonCircle;
							return tester(
								store.editor.selectionBoxAsSat,
								entity.params.asSatCircle
							);

							store.editor.addEntityToSelection(entity);
						}
						if ('params' in entity && 'asSatPolygons' in entity.params) {
							const tester = store.editor.selectionBoxAsSat instanceof Vector ? pointInPolygon : testPolygonPolygon;
							return entity.params.asSatPolygons
								.some((polygon: Polygon) => tester(store.editor.selectionBoxAsSat, polygon));

						}

						return false;
					});

					if (shortcut) {
						entitiesToAdd.forEach((entity: IEntity) => store.editor.addEntityToSelection(entity));
					} else {
						store.editor.setSelection(entitiesToAdd);
					}

					store.editor.endSelectionBox();
				}),
			)),
		)),
		ignoreElements(),
	);
}