rxjs/operators#mapTo TypeScript Examples

The following examples show how to use rxjs/operators#mapTo. 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: upload-status.guard.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot // eslint-disable-line
  ): Observable<boolean> {
    const id = route.params.id

    return this.facade.upload$.pipe(
      take(1),
      mergeMap((stateUpload) => {
        return stateUpload
          ? of(true)
          : this.fileUploadApiService.findUploadJob(id).pipe(
              tap((upload) => this.facade.setUpload(upload)),
              mapTo(true),
              catchError(() => {
                this.router.navigate([`/`])
                return of(false)
              })
            )
      })
    )
  }
Example #2
Source File: store.component.ts    From App with MIT License 6 votes vote down vote up
ngOnInit(): void {
		this.appService.subscription.pipe(
			filter(sub => sub !== null),
			switchMap(sub => this.restService.Discord.Widget().pipe(
				RestService.onlyResponse(),
				tap(d => this.discordInvite = d.body?.instant_invite ?? ''),
				catchError(() => of(sub)),
				mapTo(sub)
			)),

			// Fetch gifter?
			switchMap(sub => iif(() => !!sub?.gifter_id,
				this.restService.v2.GetUser(sub?.gifter_id as string).pipe(
					map(res => this.dataService.add('user', res.user)[0]),
					tap(u => this.gifter = u),
					mapTo(sub)
				),
				of(sub)
			))
		).subscribe({
			next: sub => {
				this.subscription.next(sub);
			}
		});

		this.appService.egvaultOK.pipe(filter(x => x !== null)).pipe(
			tap(ok => {
				this.available.next(ok);
				if (!ok) {
					this.clientService.openSnackBar('Subscription service is currenty unavailable, try again in a minute', 'OK', { duration: 3000, verticalPosition: 'top' });
					this.router.navigate(['/']);
				}
			})
		).subscribe({
			complete: () => this.cdr.markForCheck()
		});
	}
Example #3
Source File: fetch.ts    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if realtime is possible at the node. Only checks once for the current
 * node.
 */
export function canDoRealtime(
  realtimeRef: firebase.database.Reference
): Observable<boolean> {
  const silent = restUrl(realtimeRef, {
    print: 'silent',
    timeout: REST_TIMEOUT,
  });
  return defer(() => fetch(silent, { headers: ADMIN_AUTH_HEADERS })).pipe(
    mapTo(true),
    catchError(() => of(false)),
    shareReplay({ bufferSize: 1, refCount: true })
  );
}
Example #4
Source File: publication-lock.guard.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot // eslint-disable-line
  ): Observable<boolean> {
    const id = route.params.id

    return this.publishService.getPublishingStatus(id).pipe(
      tap((publication) => this.facade.setPublication(publication)),
      tap((publication: PublishJobStatusApiModel) => {
        if (publication.status === PublishStatusEnumApiModel.Done) {
          this.router.navigate([`${id}/publishok`])
        }
        if (publication.status === PublishStatusEnumApiModel.Running) {
          this.router.navigate([`${id}/publish`])
        }
      }),
      mapTo(true),
      catchError(() => {
        return of(true)
      })
    )
  }
Example #5
Source File: index.tsx    From codedoc with MIT License 6 votes vote down vote up
export function initCodeLineRef() {
  onReady(() => {
    const renderer = getRenderer();
    const target = new Subject<HTMLElement | undefined>();

    renderer.render(<RefBox target={target}/>).on(document.body);

    const _exec = () => {
      document.querySelectorAll('pre>code>div').forEach(line$ => {
        let ref = '';
        let ref$: HTMLElement | undefined;
  
        line$.querySelectorAll('.token.comment').forEach(comment$ => {
          const match = commentRegex.exec(comment$.textContent || '');
          if (match) {
            ref = match.slice(1).find(_ => _) || ref;
            if (ref) ref$ = comment$ as HTMLElement;
          }
        });
  
        if (ref.length > 0 && ref$) {
          ref$.remove();
          const match = mdlinkRegex.exec(ref);
          if (match) {
            line$.setAttribute('data-ref', match[2] || '');
            line$.setAttribute('data-ref-text', match[1] || '');
          }
          else 
            line$.setAttribute('data-ref', ref);
          fromEvent(line$, 'mouseenter').pipe(mapTo(line$ as HTMLElement)).subscribe(target);
          fromEvent(line$, 'mouseleave').pipe(mapTo(undefined)).subscribe(target);
        }
      });
    }

    _exec(); window.addEventListener('navigation', _exec);
  });
}
Example #6
Source File: subscribe-to-one-raw-search.ts    From js-client with MIT License 6 votes vote down vote up
makeSubscribeToOneRawSearch = (context: APIContext) => {
	const templatePath = '/api/ws/search';
	const url = buildURL(templatePath, { ...context, protocol: 'ws' });

	return async (): Promise<APISubscription<RawSearchMessageReceived, RawSearchMessageSent>> => {
		const socket = new WebSocket(url, context.authToken ?? undefined);
		const rawSubscription = apiSubscriptionFromWebSocket<RawSearchMessageReceived, RawSearchMessageSent>(socket);

		rawSubscription.send({ Subs: ['PONG', 'parse', 'search', 'attach'] });

		const wsClosed$: Observable<void> = rawSubscription.sent$.pipe(
			startWith(undefined),
			// Even if the websocket hangs up due to an error, we want to emit, so that we can
			// clean up the PONG subscription below
			catchError(() => of(undefined)),
			mapTo(undefined),
			last(),
		);

		timer(1000, 5000)
			.pipe(takeUntil(wsClosed$))
			.subscribe(() => {
				rawSubscription.send({ type: 'PONG', data: {} });
			});

		return rawSubscription;
	};
}
Example #7
Source File: dyn-providers.ts    From open-source with MIT License 6 votes vote down vote up
/**
 * Related Condition
 */
function relatedConditionFn({ path, value, field, negate }: DynControlRelated): DynControlConditionFn {
  return (node: DynTreeNode) => {
    const control = node.query(path);
    if (!control) {
      console.error(`Control '${path}' not found inside a Condition`)
      return of(true); // do not break AND matchers
    }
    if (value === undefined) {
      // triggers with any valueChange
      return control.valueChanges.pipe(
        startWith(control.value),
        mapTo(true),
      );
    }
    return control.valueChanges.pipe(
      startWith(control.value),
      // compare the configured value
      map(controlValue => field && isPlainObject(controlValue)
        ? controlValue[field]
        : controlValue
      ),
      map(controlValue => {
        return Array.isArray(value)
          ? value.includes(controlValue)
          : value === controlValue;
      }),
      // negate the result if needed
      map(result => negate ? !result : result),
    );
  }
}
Example #8
Source File: android-back-button.service.ts    From capture-lite with GNU General Public License v3.0 6 votes vote down vote up
closeMatDialog$<T>(dialogRef: MatDialogRef<T>, priority = 100) {
    return this.androidBackButtonEvent$.pipe(
      tap((event: any) =>
        event.detail.register(priority, () =>
          this.zone.run(() => dialogRef.close())
        )
      ),
      mapTo(dialogRef)
    );
  }
Example #9
Source File: mockApiRx.ts    From guardian with Apache License 2.0 6 votes vote down vote up
MockApiRx = of({
  ...acalaRpc,
  consts: {
    prices: { stableCurrencyFixedPrice: 1e18 },
    currencies: { getNativeCurrencyId: ACA },
    cdpEngine: {
      getStableCurrencyId: AUSD,
      collateralCurrencyIds: COLLATERAL_CURRENCY_IDS
    }
  },
  query: {
    auctionManager: {
      collateralAuctions: {
        entries: () => of([[collateralAuctionsKey(0), COLLATERAL_AUCTION]])
      }
    },
    auction: {
      auctionsIndex: () => of(registry.createType('AuctionId', 1)),
      auctions: () => of(AUCTION)
    },
    dex: {
      liquidityPool: () => of(LP)
    },
    loans: {
      positions: () => of(POSITION)
    },
    cdpEngine: {
      debitExchangeRate: () => of(EXCHANGE_RATE)
    },
    acalaOracle: {
      values: () => {
        return merge([of(PRICE), timer(1000).pipe(mapTo(PRICE_UPDATED))]).pipe(concatAll(), share());
      }
    }
  },
  createType: (type: string, value: any) => registry.createType(type, value)
})
Example #10
Source File: subscriber-route-handler.ts    From pebula-node with MIT License 6 votes vote down vote up
private createPipeHandler(metadata: SbSubscriberMetadata<T>, handler: OperatorFunction<SbContext, SbContext>, routeInstructions: RouteToCommit) {
    const consumer = createConsumer(routeInstructions);

    return async (message: ServiceBusMessage) => {
      const context = new SbContext([metadata, message]);
      const done = async () => handler(of(context)).pipe(mapTo(context)).toPromise();
      await consumer.intercept(context, done).then(safeResolveResult).catch(WrappedError.wrapPromise);
    };
  }
Example #11
Source File: rest-v2.structure.ts    From App with MIT License 6 votes vote down vote up
BanUser(victimID: string, expireAt: Date, reason = ''): Observable<void> {
		return this.gql.query<{}>({
			query: `
				mutation BanUser($usr: String!, $ex: String, $rsn: String) {
					banUser(victim_id: $usr, expire_at: $ex, reason: $rsn) {
						status, message
					}
				}
			`,
			variables: {
				usr: victimID,
				ex: expireAt.toISOString(),
				rsn: reason
			},
			auth: true
		}).pipe(mapTo(undefined));
	}
Example #12
Source File: index.tsx    From codedoc with MIT License 6 votes vote down vote up
export function initHintBox() {
  onReady(() => {
    const renderer = getRenderer();
    const target = new Subject<HTMLElement | undefined>();
  
    renderer.render(<HintBox target={target}/>).on(document.body);

    const _exec = () => {
      document.querySelectorAll('pre>code>div').forEach(line$ => {
        let hint = ''; 
        let hint$: HTMLElement | undefined;
        line$.querySelectorAll('.token.comment').forEach(comment$ => {
          const match = commentRegex.exec(comment$.textContent || '');
          if (match) {
            hint = match.slice(1).find(_ => _) || hint;
            if (hint) hint$ = comment$ as HTMLElement;
          }
        });
  
        if (hint.length > 0 && hint$) {
          hint$.style.opacity = '.5';
          line$.setAttribute('data-hint', hint);
          fromEvent(line$, 'mouseenter').pipe(mapTo(line$ as HTMLElement)).subscribe(target);
          fromEvent(line$, 'mouseleave').pipe(mapTo(undefined)).subscribe(target);
        }
      });
    }

    _exec(); window.addEventListener('navigation', _exec);
  });
}
Example #13
Source File: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
mockConfirmEpic: EpicSignature = (action$, state$, deps) => {
  return action$.pipe(
    filter(isActionOf(Actions.setTransactionStage)),
    pluck("payload"),
    filter(x => x === "SIGN"),
    filter(() => state$.value.polkadot.interactionType !== "ACTIVATE"),
    delay(3000),
    mapTo(Actions.setTransactionStage("CONFIRMED")),
  );
}
Example #14
Source File: tokens-select.component.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Fetches token's image url.
   * @param token Token to display.
   * @return Promise<string> Token image url.
   */
  private fetchTokenImage(token: BlockchainToken): Promise<string> {
    const blockchains = {
      [BLOCKCHAIN_NAME.ETHEREUM]: 'ethereum',
      [BLOCKCHAIN_NAME.BINANCE_SMART_CHAIN]: 'smartchain',
      [BLOCKCHAIN_NAME.POLYGON]: 'polygon',
      [BLOCKCHAIN_NAME.MOONRIVER]: 'moonriver',
      [BLOCKCHAIN_NAME.FANTOM]: 'fantom',
      [BLOCKCHAIN_NAME.ARBITRUM]: 'arbitrum',
      [BLOCKCHAIN_NAME.AURORA]: 'aurora',
      [BLOCKCHAIN_NAME.TELOS]: 'telos'
    };
    const image = `https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/${
      blockchains[token.blockchain as keyof typeof blockchains]
    }/assets/${EthLikeWeb3Public.toChecksumAddress(token.address)}/logo.png`;

    return this.httpClient
      .get(image)
      .pipe(
        mapTo(image),
        catchError((err: unknown) => {
          return (err as HttpErrorResponse)?.status === 200 ? of(image) : of(DEFAULT_TOKEN_IMAGE);
        })
      )
      .toPromise();
  }
Example #15
Source File: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
/* ------------------------------------------------------------------------- */

/**
 * Recursively create the given directory
 *
 * @param directory - Directory
 *
 * @returns Directory observable
 */
export function mkdir(directory: string): Observable<string> {
  return defer(() => fs.mkdir(directory, { recursive: true }))
    .pipe(
      mapTo(directory)
    )
}
Example #16
Source File: clipboard.service.ts    From RcloneNg with MIT License 6 votes vote down vote up
constructor(private tasksQueueService: TasksQueueService) {
		super();
		const outer = this;
		this.clipboard$ = new (class extends ClipboardFlow {
			public prerequest$ = outer.trigger.pipe(
				mapTo<number, CombErr<ClipboardFlowNode>>([{ clipboard: outer }, []])
			);
		})();
		this.clipboard$.deploy();
		this.clipboard$.getOutput().subscribe();
		this.trigger.next(1);
	}
Example #17
Source File: product-quick-create.component.ts    From pantry_party with Apache License 2.0 6 votes vote down vote up
createNewProduct() {
    return this.grocyService.createProduct({
      ...this.createProductBaseParams(),
      name: this.product.name,
      cumulate_min_stock_amount_of_sub_products: false,
      min_stock_amount: this.product.minStockAmount,
      parent_product_id: this.product.parent_product_id,
    }).pipe(
      switchMap(r => this.grocyService.createProductBarcode({
        product_id: r.id,
        amount: `${this.product.quantityUnitFactor}`,
        qu_id: this.product.purchaseQuantityUnits.id,
        barcode: this.product.barcode,
      }).pipe(mapTo(r))
      )
    );
  }
Example #18
Source File: emote.component.ts    From App with MIT License 6 votes vote down vote up
/**
	 * Method called when the client user interacts with a button
	 */
	onInteract(interaction: ContextMenuComponent.InteractButton): void {
		if (typeof interaction.click === 'function' && !!this.emote) {
			interaction.click(this.emote).pipe(
				switchMap(() => iif(() => interaction.label === 'add to channel' || interaction.label === 'remove from channel',
					this.readChannels().pipe(mapTo(undefined)),
					of(undefined)
				))
			).subscribe({
				complete: () => this.interactError.next(''),
				error: (err: HttpErrorResponse) => this.interactError.next(this.restService.formatError(err))
			});
		}
	}
Example #19
Source File: builder.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
/**
 * @experimental Direct usage of this function is considered experimental.
 */
export function execute(
  options: any,
  context: BuilderContext
): Observable<BuilderOutput> {
  return from(
    (async () => {
      const root = context.workspaceRoot;
      let tsConfig: string | undefined;

      if (options.tsConfig) {
        tsConfig = resolve(root, options.tsConfig);
      }
      const packager = await ngPackagrFactory(
        resolve(root, options.project),
        tsConfig
      );

      const projectName = context.target?.project;
      if (!projectName) {
        throw new Error('The builder requires a target.');
      }

      const metadata = await context.getProjectMetadata(projectName);
      const { enabled: cacheEnabled, path: cacheDirectory } =
        normalizeCacheOptions(metadata, context.workspaceRoot);

      const ngPackagrOptions = {
        cacheEnabled,
        cacheDirectory: join(cacheDirectory, 'ng-packagr'),
      };

      return { packager, ngPackagrOptions };
    })()
  ).pipe(
    switchMap(({ packager, ngPackagrOptions }) =>
      options.watch
        ? packager.watch(ngPackagrOptions)
        : packager.build(ngPackagrOptions)
    ),
    mapTo({ success: true, workspaceRoot: context.workspaceRoot }),
    catchError((err) => of({ success: false, error: err.message }))
  );
}
Example #20
Source File: runRequest.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
/**
 * This function handles the excecution of requests & and processes the single or multiple response packets into
 * a combined PanelData response.
 * It will
 *  * Merge multiple responses into a single DataFrame array based on the packet key
 *  * Will emit a loading state if no response after 50ms
 *  * Cancel any still running network requests on unsubscribe (using request.requestId)
 */
export function runRequest(datasource: DataSourceApi, request: DataQueryRequest): Observable<PanelData> {
  let state: RunningQueryState = {
    panelData: {
      state: LoadingState.Loading,
      series: [],
      request: request,
      timeRange: request.range,
    },
    packets: {},
  };

  // Return early if there are no queries to run
  if (!request.targets.length) {
    request.endTime = Date.now();
    state.panelData.state = LoadingState.Done;
    return of(state.panelData);
  }

  const dataObservable = callQueryMethod(datasource, request).pipe(
    // Transform response packets into PanelData with merged results
    map((packet: DataQueryResponse) => {
      if (!isArray(packet.data)) {
        throw new Error(`Expected response data to be array, got ${typeof packet.data}.`);
      }

      request.endTime = Date.now();

      state = processResponsePacket(packet, state);

      return state.panelData;
    }),
    // handle errors
    catchError(err =>
      of({
        ...state.panelData,
        state: LoadingState.Error,
        error: processQueryError(err),
      })
    ),
    tap(getAnalyticsProcessor(datasource)),
    // finalize is triggered when subscriber unsubscribes
    // This makes sure any still running network requests are cancelled
    finalize(cancelNetworkRequestsOnUnsubscribe(request)),
    // this makes it possible to share this observable in takeUntil
    share()
  );

  // If 50ms without a response emit a loading state
  // mapTo will translate the timer event into state.panelData (which has state set to loading)
  // takeUntil will cancel the timer emit when first response packet is received on the dataObservable
  return merge(timer(200).pipe(mapTo(state.panelData), takeUntil(dataObservable)), dataObservable);
}
Example #21
Source File: user-home.component.ts    From App with MIT License 5 votes vote down vote up
ngOnInit(): void {
		this.user.pipe(
			filter(user => !!user && AppComponent.isBrowser.getValue()),
			takeUntil(this.destroyed),
			tap(user => this.currentUser = user),
			tap(user => this.emoteSlots.next(user.getSnapshot()?.emote_slots ?? 0)),

			switchMap(user => user.getAuditEntries().pipe(
				tap(entries => this.auditEntries = entries),
				mapTo(user)
			)),
			switchMap(user => user.isLive().pipe(
				map(live => this.isLive.next(live)),
				switchMap(() => user.getBroadcast()),
				map(broadcast => this.broadcast.next(broadcast)),
				mapTo(user)
			)),
			switchMap(user => scheduled([
				user.getEmotes().pipe(map(emotes => ({ type: 'channel', emotes }))),
				user.getOwnedEmotes().pipe(map(emotes => ({ type: 'owned', emotes })))
			], asapScheduler).pipe(
				concatAll(),
				mergeMap(s => from(s.emotes).pipe(
					mergeMap(em => this.shouldBlurEmote(em).pipe(map(blur => ({ blur, emote: em })))),
					map(x => x.blur ? this.blurred.add(x.emote.getID()) : noop()),
					toArray(),
					mapTo(s)
				)),
				take(2),
			))
		).subscribe({
			next: set => {
				switch (set.type) {
					case 'channel':
						this.channelEmotes = set.emotes;
						this.channelCount.next(set.emotes.length);
						break;
					case 'owned':
						this.ownedEmotes = set.emotes;
						this.ownedCount.next(set.emotes.length);
						break;
				}
			}
		});
	}
Example #22
Source File: rx-operators.ts    From ionic-pwa-example-moment with MIT License 5 votes vote down vote up
export function concatTap<T>(
  func: (value: T) => Observable<any> | Promise<any>
) {
  return (source$: Observable<T>) =>
    source$.pipe(concatMap(value => from(func(value)).pipe(mapTo(value))));
}
Example #23
Source File: user.component.ts    From App with MIT License 5 votes vote down vote up
ngOnInit(): void {
		this.route.paramMap.pipe(
			takeUntil(this.destroyed),
			map(params => params.get('user') as string),
			switchMap(id => this.restService.v2.GetUser(id, {
				includeEditors: true,
				includeEditorIn: true,
				includeOwnedEmotes: true,
				includeFullEmotes: true,
				includeAuditLogs: true,
				includeStreamData: true
			}, ['banned', 'youtube_id']).pipe(
				map(res => this.dataService.add('user', res.user)[0])
			)),
			tap(user => this.user.next(user)),
			switchMap(user => scheduled([
				user.getEditors().pipe(map(editors => this.editors.next(editors))),
				user.getEditorIn().pipe(map(edited => this.edited.next(edited))),
				user.getYouTubeID().pipe(tap(ytid => this.hasYouTube.next(ytid !== null)), switchMapTo(EMPTY))
			], asyncScheduler).pipe(concatAll(), mapTo(user))),
			tap(user => {
				const appURL = this.document.location.host + this.router.serializeUrl(this.router.createUrlTree(['/users', String(user.id)]));

				this.appService.pageTitleAttr.next([ // Update page title
					{ name: 'User', value: user.getSnapshot()?.display_name ?? '' }
				]);
				const roleName = user.getSnapshot()?.role?.name;
				const roleColor = user.getSnapshot()?.role?.color;
				const emoteCount = user.getSnapshot()?.emotes.length;
				const maxEmoteCount = user.getSnapshot()?.emote_slots;
				const displayName = user.getSnapshot()?.display_name ?? '';
				this.metaService.addTags([
					// { name: 'og:title', content: this.appService.pageTitle },
					// { name: 'og:site_name', content: this.appService.pageTitle },
					{ name: 'og:description', content: `${displayName} is${!!roleName ? ` ${roleName}` : ''} on 7TV with ${emoteCount}/${maxEmoteCount} emotes enabled`},
					{ name: 'og:image', content: user.getSnapshot()?.profile_image_url ?? '' },
					{ name: 'og:image:type', content: 'image/png' },
					{ name: 'theme-color', content: (roleColor ? `#${roleColor.toString(16)}` : '#fff') }
				]);

				if (!AppComponent.isBrowser.getValue()) {
					const link = this.document.createElement('link');
					link.setAttribute('type', 'application/json+oembed');

					const query = new URLSearchParams();
					query.append('object', Buffer.from(JSON.stringify({
						title: this.appService.pageTitle,
						author_name: displayName,
						author_url: `https://${appURL}`,
						provider_name: `7TV.APP - It's like a third party thing`,
						provider_url: 'https://7tv.app'
					})).toString('base64'));
					link.setAttribute('href', `https://${environment.origin}/services/oembed?` + query.toString());
					this.document.head.appendChild(link);
				}
			})
		).subscribe({
			error: (err) => this.loggerService.error('Couldn\'t fetch user', err)
		});
	}
Example #24
Source File: rx-operators.ts    From capture-lite with GNU General Public License v3.0 5 votes vote down vote up
export function switchTapTo<T>(observable$: Observable<any>) {
  return (source$: Observable<T>) =>
    source$.pipe(switchMap(value => observable$.pipe(mapTo(value))));
}
Example #25
Source File: index.ts    From open-source with MIT License 5 votes vote down vote up
function gitCheck<T>(files: T): Observable<T> {
  return exec('git', ['status']).pipe(
    mapTo(files),
    catchError(() => throwError('Do not use --git outside a repository')),
  );
}
Example #26
Source File: SignIn.use-case.ts    From rn-clean-architecture-template with MIT License 5 votes vote down vote up
onRemoteSignInSuccess(result: SignInResult): Observable<SignInResult> {
    return this.authenticationRepository
      .saveToken('test', result.token)
      .pipe(mapTo(result));
  }
Example #27
Source File: subscribe-to-query-parsing.ts    From js-client with MIT License 5 votes vote down vote up
makeSubscribeToOneQueryParsing = (context: APIContext) => {
	const templatePath = '/api/ws/search';
	const url = buildURL(templatePath, { ...context, protocol: 'ws' });

	return async (): Promise<
		APISubscription<ValidatedQuery & { id: number }, { id: number; query: Query; filters: Array<ElementFilter> }>
	> => {
		const socket = new WebSocket(url, context.authToken ?? undefined);
		const rawSubscription = apiSubscriptionFromWebSocket<
			RawQueryValidationMessageReceived,
			RawQueryValidationMessageSent
		>(socket);
		rawSubscription.send({ Subs: ['PONG', 'parse', 'search', 'attach'] });
		const wsClosed$: Observable<void> = rawSubscription.sent$.pipe(startWith(undefined), mapTo(undefined), last());
		timer(1000, 5000)
			.pipe(takeUntil(wsClosed$))
			.subscribe(() => {
				rawSubscription.send({ type: 'PONG', data: {} });
			});

		const received$ = rawSubscription.received$.pipe(
			filter((msg): msg is RawQueryValidationDesiredMessageReceived => {
				try {
					return (msg as RawQueryValidationDesiredMessageReceived)?.type === 'parse';
				} catch {
					return false;
				}
			}),
			map(msg => ({ ...toValidatedQuery(msg.data), id: msg.data.Sequence })),
		);

		const sent$ = rawSubscription.sent$.pipe(
			filter((msg): msg is RawQueryValidationDesiredMessageSent => {
				try {
					return (msg as RawQueryValidationDesiredMessageSent)?.type === 'parse';
				} catch {
					return false;
				}
			}),
			map(msg => ({
				id: msg.data.Sequence,
				query: msg.data.SearchString,
				filters: (msg.data.Filters ?? []).map(toElementFilter),
			})),
		);

		const received: Array<ValidatedQuery & { id: number }> = [];
		const sent: Array<{ id: number; query: Query; filters: Array<ElementFilter> }> = [];

		received$.subscribe(receivedMessage => received.push(receivedMessage));
		sent$.subscribe(sentMessage => sent.push(sentMessage));

		return {
			close: () => rawSubscription.close(),
			send: async msg => {
				const rawMsg: RawQueryValidationMessageSent = {
					type: 'parse',
					data: {
						SearchString: msg.query,
						Sequence: msg.id,
					},
				};
				if (msg.filters.length !== 0)
					rawMsg.data.Filters = msg.filters.map(f => ({
						Tag: f.tag,
						Module: f.module,
						Path: f.path,
						Args: f.arguments ?? undefined,
						Op: f.operation,
						Value: f.value,
					}));
				await rawSubscription.send(rawMsg);
			},
			received$,
			received,
			sent$,
			sent,
		};
	};
}
Example #28
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(),
	);
}
Example #29
Source File: index.ts    From open-source with MIT License 4 votes vote down vote up
treeVisit(opts.path).pipe(
  filter((file) => opts.isValid(file)),
  waitForAll(),
  concatMap((files) => opts.git ? gitCheck(files) : of(files)),
  concatMap(files => from(files)),
  // diagnose
  concatMap((file) => {
    logInfo('-', relative(dirname(opts.path), file));
    if (opts.onlyDiagnose) {
      counter++;
    }
    return opts.shouldAnalize(file)
      ? replaceCRLF(opts.withFile(file)).pipe(
          concatMap(() => opts.onlyDiagnose ? of(file) : stylusParse(opts.withFile(file))),
          catchError((err) => {
            logNote(`stylusParse error at ${relative(dirname(opts.path), file)}`);
            return throwError(err);
          }),
          mapTo(file),
        )
      : of(file);
  }),
  waitForAll(),
  concatMap(files => from(files)),
  // convert
  concatMap((file) => {
    if (opts.shouldConvert(file)) {
      return stylusConvert(opts.withFile(file)).pipe(
        concatMap(() => opts.git
          ? exec('git', ['add', file], { dryRun: opts.dryRun }).pipe(
              catchError(() => of({})),
            )
          : of({}),
        ),
        catchError((err) => {
          logNote(`stylusConvert error at ${relative(dirname(opts.path), file)}`);
          return throwError(err);
        }),
        mapTo(file),
      );
    }
    return of(file);
  }),
  waitForAll(),
  concatMap((files) => {
    return opts.shouldConvertCommit()
      ? gitCommit(files, 'Message for the convert commit:')
      : of(files);
  }),
  concatMap(files => from(files)),
  // move
  concatMap((file) => {
    if (opts.shouldCheckComponent(file)) {
      const tsFile = file.replace(/\.styl$/, `.ts`);
      return componentUpdate(opts.withFile(tsFile)).pipe(
        concatMap(() => opts.git
          ? exec('git', ['add', tsFile], { dryRun: opts.dryRun }).pipe(delay(50), mapTo(file))
          : of(file)
        ),
        catchError(() => of(file)),
      );
    }
    return of(file);
  }),
  waitForAll(),
  concatMap(files => from(files)),
  concatMap((file) => {
    if (opts.shouldMove(file)) {
      logInfo('+', relative(dirname(opts.path), file));
      counter++;
      const newFile = file.replace(/\.styl$/, `.scss`);
      return opts.git
        ? exec('git', ['mv', file, newFile], { dryRun: opts.dryRun }).pipe(delay(50), mapTo(newFile))
        : !opts.dryRun
          ? renameFile(file, newFile).pipe(mapTo(newFile))
          : logInfo(`> mv ${file} ${newFile}`) || of(newFile);
    }
    return of(file);
  }),
  waitForAll(),
  concatMap((files) => {
    return opts.shouldCommitMove()
      ? gitCommit(files, 'Message for the move commit:')
      : of(files);
  }),
  concatMap(files => from(files)),
  // migrate
  concatMap((file) => {
    if (opts.shouldMigrate(file)) {
      if (opts.onlyMigrate) {
        logInfo('>', relative(dirname(opts.path), file));
        counter++;
      }
      const args: string[] = ['sass-migrator', 'division', opts.dryRun ? '--dry-run' : null, file].filter(Boolean);
      return exec('npx', args, { cwd: __dirname, dryRun: opts.dryRun }).pipe(
        concatMap(() => exec('git', ['add', file], { dryRun: opts.dryRun }).pipe(
          catchError(() => of(file)),
        )),
        mapTo(file),
        catchError((err) => {
          console.error(err);
          return throwError(err);
        }),
      );
    }
    return of(file);
  }),
  waitForAll(),
  concatMap((files) => {
    return opts.shouldCommitMigration()
      ? gitCommit(files, 'Message for the migrate commit:')
      : of(files);
  }),
).subscribe({
  error: (err) => logNote(err),
  complete: () => logNote(`${counter} files ${opts.onlyDiagnose ? 'to process' : 'processed'}`),
});