rxjs#fromEvent TypeScript Examples

The following examples show how to use rxjs#fromEvent. 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: sticky-header.component.ts    From geonetwork-ui with GNU General Public License v2.0 7 votes vote down vote up
ngAfterViewInit() {
    this.scrollSub = fromEvent(this.scrollableParent, 'scroll', {
      passive: true,
    })
      .pipe(
        throttleTime(0, animationFrameScheduler, {
          leading: true,
          trailing: true,
        })
      )
      .subscribe(this.updateSize.bind(this))
  }
Example #2
Source File: leaderboard.component.ts    From one-platform with MIT License 6 votes vote down vote up
ngAfterViewInit() {
    this.searchSubscription = fromEvent(this.searchInput.nativeElement, 'keyup')
      .pipe(
        map((event: InputEvent) => (event.target as HTMLInputElement).value),
        debounceTime(500),
        distinctUntilChanged()
      )
      .subscribe((search) => {
        this.searchTerm = search;
        this.pageOffset = 0;
        this.fetchLHLeaderboard();
      });
  }
Example #3
Source File: component.tsx    From codedoc with MIT License 6 votes vote down vote up
export function HintBox(
  this: ThemedComponentThis<CodedocTheme>,
  _: any, 
  renderer: any
) {
  const classes = this.theme.classes(HintBoxStyle);
  const target$ = this.expose.in('target', new Subject<HTMLElement | undefined>());
  const active$ = target$.pipe(map(el => !!el));
  const top$ = combineLatest(
      target$
        .pipe(
          map(el => el ? el.getBoundingClientRect().top : undefined)
        ), 
      fromEvent(document, 'mousemove')
        .pipe(
          map(e => (e as MouseEvent).clientY)
        )
    ).pipe(
      map(([top, mouseY]) => (top || mouseY) + 24)
    );
  const left$ = fromEvent(document, 'mousemove').pipe(map(e => (e as MouseEvent).clientX + 24));

  return <div 
      class={rl`${classes.hintbox} ${toggleList({'active': active$.pipe(startWith(false))})}`}
      style={rl`top: ${top$}px;left: ${left$}px`}
    >
    <span class="icon-font outline">wb_incandescent</span>
    {target$.pipe(filter(el => !!el), map(el => el?.getAttribute('data-hint')))}
  </div>;
}
Example #4
Source File: faq.component.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Scrolls page to query params anchor.
   */
  private scrollToAnchorItem(): void {
    setTimeout(() => {
      if (this.anchor) {
        const answerElement = this.element.nativeElement.querySelector(`#${this.anchor}`);

        if (!answerElement) {
          return;
        }

        answerElement.scrollIntoView({ behavior: 'smooth' });
        fromEvent(document, 'scroll').pipe(debounceTime(50), takeUntil(this.destroy$)).subscribe();
      }
    }, 200);
  }
Example #5
Source File: echarts.component.ts    From ng-devui-admin with MIT License 6 votes vote down vote up
ngAfterViewInit(): void {
    if (!this.theme && this.themeService && this.themeService.eventBus) {
      this.themeService.eventBus.add('themeChanged', this.themeChange);
    }
    this.initTheme();
    this.echart = (<any>echarts).init(this.elementRef.nativeElement, this.theme);
    this.updateChartData(this.options);
    this.chartReady.emit(this.echart);
    // 根据浏览器大小变化自动调整echarts
    if (this.autoResize) {
      this.resizeSub = fromEvent(window, 'resize')
        .pipe(debounceTime(100))
        .subscribe(() => {
          this.echart.resize();
        });
    }
  }
Example #6
Source File: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
/**
 * Watch all files matching the given pattern
 *
 * @param pattern - Pattern
 * @param options - Options
 *
 * @returns File observable
 */
export function watch(
  pattern: string, options: WatchOptions
): Observable<string> {
  return fromEvent(
    chokidar.watch(pattern, options),
    "change"
  ) as Observable<string>
}
Example #7
Source File: ion-media-cache.directive.ts    From ion-media-cache with MIT License 6 votes vote down vote up
constructor(
    private el: ElementRef,
    private file: File,
    private renderer: Renderer2,
    private platform: Platform,
    private webview: WebView) {
    this.tag = this.el;
    if (!window['IonMediaCache']) {
      window['IonMediaCache'] = {};
    }
    if (this.isMobile) {
      fromEvent(document, 'deviceready').pipe(first()).subscribe(res => {
        this.initCache();
      });
    } else {
      this.initCache();
    }
  }
Example #8
Source File: bill-of-materials.component.ts    From barista with Apache License 2.0 6 votes vote down vote up
ngAfterViewInit(): void {
    if (!this.searchInput) {
      return;
    }

    fromEvent(this.searchInput.nativeElement, 'input')
      .pipe(
        map((event: any) => event.target.value),
        filter(res => res.length > 2 || res.length === 0),
        debounceTime(500),
        distinctUntilChanged(),
        untilDestroyed(this),
      )
      .subscribe((text: string) => {
        this.bomGlobalFilterMessageService.send(text);
      });
  }
Example #9
Source File: data-studio.service.ts    From visualization with MIT License 6 votes vote down vote up
constructor(
    @Inject(WINDOW) private readonly window: Window,
    @Inject(MERMAID) private readonly mermaid: Mermaid,
    private readonly alert: AlertService) {

    this.initializeMermaid();
    const azEvent$ = fromEvent<Event>(this.window, 'message').pipe(
      tap(event => {
        if (event.data.status === Status.Error) {
          this.alert.showError({
            status: event.data.status,
            errors: event.data.errors,
            rawData: JSON.stringify(event.data.rawData)
          });
        }
      })
    );

    this.status$ = concat(azEvent$.pipe(
      map(e => e.data?.status),

    ));

    this.database$ = azEvent$.pipe(
      filter(event => event.data?.status === Status.Complete),
      map(event => event.data?.chart),
      switchMap(r => this.buildSvg(r))
    );



    this.databaseName$ = azEvent$.pipe(
      filter(event => event.data?.status === Status.Complete),
      map(event => event.data?.databaseName));
  }
Example #10
Source File: router-outlet-context-provider.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
constructor(iframe: HTMLIFrameElement) {
    // Listen for requests from embedded web content of the outlet.
    this._microfrontendRequest$ = fromEvent<MessageEvent>(window, 'message')
      .pipe(
        filter(event => event.source === iframe.contentWindow),
        filterByTransport(MessagingTransport.MicrofrontendToOutlet),
        filterByChannel<TopicMessage>(MessagingChannel.Topic),
        share(),
      );
  }
Example #11
Source File: my-addons.component.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public ngAfterViewInit(): void {
    this._sessionService.myAddonsCompactVersion = !this.getLatestVersionColumnVisible();

    if (this.addonFilter?.nativeElement !== undefined) {
      const addonFilterSub = fromEvent(this.addonFilter.nativeElement as HasEventTargetAddRemove<unknown>, "keyup")
        .pipe(
          filter(Boolean),
          debounceTime(200),
          distinctUntilChanged(),
          tap(() => {
            const val: string = this.addonFilter.nativeElement.value.toString();
            console.debug(val);
            this._filterInputSrc.next(val);
          })
        )
        .subscribe();

      this._subscriptions.push(addonFilterSub);
    }

    this._sessionService.autoUpdateComplete$
      .pipe(
        tap(() => console.log("Checking for addon updates...")),
        switchMap(() => from(this.loadAddons()))
      )
      .subscribe(() => {
        this._cdRef.markForCheck();
      });
  }
Example #12
Source File: anchor.directive.ts    From alauda-ui with MIT License 6 votes vote down vote up
adaptAnchorPosition(containerEl: HTMLElement, anchorEl: HTMLElement) {
    const pageContentEl = containerEl.closest('.aui-page__content');
    const anchorContentEl = anchorEl.querySelector('.aui-anchor');

    merge(observeResizeOn(containerEl), fromEvent(window, 'scroll'))
      .pipe(startWith(null as void), takeUntil(this.destroy$$))
      .subscribe(() => {
        const containerRect = containerEl.getBoundingClientRect();
        Object.assign(anchorEl.style, {
          display: !containerRect.width || !containerRect.height ? 'none' : '',
          left:
            containerRect.right -
            anchorContentEl.getBoundingClientRect().width +
            'px',
          top:
            Math.max(
              containerRect.top,
              (this.minTop ??
                (pageContentEl &&
                  +getComputedStyle(pageContentEl).paddingTop.slice(0, -2))) ||
                0,
            ) + 'px',
        });
      });

    if (this.adaptPosition) {
      observeResizeOn(anchorContentEl)
        .pipe(takeUntil(this.destroy$$))
        .subscribe(el => {
          const width = el.getBoundingClientRect().width;
          const padding = width + this.padding;
          containerEl.style.paddingRight = padding + 'px';
        });
    }
  }
Example #13
Source File: getRichVisibleRectsStream.tsx    From ali-react-table with MIT License 6 votes vote down vote up
function fromResizeEvent(element: HTMLElement | Window): Observable<Event | ResizeObserverEntry[]> {
  if (isWindow(element)) {
    return fromEvent<Event>(element, 'resize', { passive: true })
  }

  return new Observable((subscriber) => {
    const resizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) => {
      subscriber.next(entries)
    })
    resizeObserver.observe(element as HTMLElement)

    return () => {
      resizeObserver.disconnect()
    }
  })
}
Example #14
Source File: expenses.component.ts    From budget-angular with GNU General Public License v3.0 6 votes vote down vote up
ngAfterViewInit() {
    this.keyupSubscription = fromEvent(this.filter.nativeElement, "keyup")
      .pipe(
        debounceTime(1000),
        map((event: Event) => (<HTMLInputElement>event.target).value),
        distinctUntilChanged(),
        tap(() => (this.isLoading = true)),
        switchMap((value) =>
          this.expensesService.filterExpenses(this.period, value)
        )
      )
      .subscribe((data) => {
        this.isLoading = false;
        this.dataSource.data = data;
      });
  }
Example #15
Source File: app-bar.component.ts    From angular-component-library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private _listenForScrollEvents(): void {
        this._setScrollEl();
        this._resizeOnModeChange();
        this._stopListeningForScrollEvents();
        this.viewInit = true;
        if (this.scrollEl) {
            this.scrollListener = fromEvent(this.scrollEl, 'scroll')
                .pipe(throttle(() => interval(10)))
                .subscribe(() => {
                    this._resizeEl();
                });

            this.resizeListener = fromEvent(window, 'resize')
                .pipe(throttle(() => interval(10)))
                .subscribe(() => {
                    this._resizeEl();
                });
        }
    }
Example #16
Source File: notes-editor.component.ts    From attack-workbench-frontend with Apache License 2.0 6 votes vote down vote up
ngAfterViewInit() {
        // search input listener
        fromEvent(this.search.nativeElement, 'keyup').pipe(
            filter(Boolean),
            debounceTime(250),
            distinctUntilChanged(),
            tap(_ => { this.parseNotes(); })
        ).subscribe();
    }
Example #17
Source File: fy-currency-choose-currency.component.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
ngAfterViewInit(): void {
    this.filteredCurrencies$ = fromEvent(this.searchBarRef.nativeElement, 'keyup').pipe(
      map((event: any) => event.srcElement.value),
      startWith(''),
      distinctUntilChanged(),
      switchMap((searchText) =>
        this.currencies$.pipe(
          map((currencies) =>
            currencies.filter(
              (currency) =>
                currency.shortCode.toLowerCase().includes(searchText.toLowerCase()) ||
                currency.longName.toLowerCase().includes(searchText.toLowerCase())
            )
          )
        )
      )
    );
  }
Example #18
Source File: facet-block.component.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
ngAfterViewInit(): void {
    if (this.eltFilterInputRef) {
      this.subscription.add(
        fromEvent<Event>(this.eltFilterInputRef.nativeElement, 'keyup')
          .pipe(debounceTime(300))
          .subscribe((event: any) =>
            this.onFilterChange((event.path[0] as HTMLInputElement).value)
          )
      )
    }
  }
Example #19
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 #20
Source File: tour-backdrop.service.ts    From ngx-ui-tour with MIT License 6 votes vote down vote up
private subscribeToWindowResizeEvent() {
        const resizeObservable$ = fromEvent(window, 'resize');
        this.windowResizeSubscription$ = resizeObservable$
            .pipe(
                debounce(() => interval(10))
            )
            .subscribe(
                () => {
                    this.setBackdropElStyles();
                    ScrollingUtil.ensureVisible(this.targetHtmlElement);
                }
            );
    }
Example #21
Source File: appinstall.service.ts    From avid-covider with MIT License 6 votes vote down vote up
constructor() {
    fromEvent(window, 'beforeinstallprompt').subscribe(($event) => {
      $event.preventDefault();
      this.installPrompt = $event;
      this.platforms = this.installPrompt.platforms || [];
      this.prompts = [];
      for (const platform of this.platforms) {
        this.prompts.push(() => this.installPrompt.prompt());
      }
    });
  }
Example #22
Source File: lazy-scroll.component.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
ngAfterViewInit(): void {
    this.lazyServiceService.adHost = this.adHost;
    this.zone.runOutsideAngular(() => {
      fromEvent(window, 'scroll', <AddEventListenerOptions>passiveEventListenerOptions).pipe(
        debounceTime(50),
        filter(() => {
          return window.scrollY >= 200;
        }),
        take(1),
        takeUntil(this.destroyService$)
      ).subscribe(() => {
        this.lazyServiceService.create().then(()=>{
          this.cdr.detectChanges();
        })
      })
    })
  }
Example #23
Source File: utils.ts    From elements with MIT License 6 votes vote down vote up
proxyOutputs = (instance: any, el: any, events: string[]) => {
  events.forEach(eventName => instance[eventName] = fromEvent(el, eventName));
}
Example #24
Source File: monaco-editor-base.component.ts    From ng-util with MIT License 6 votes vote down vote up
protected registerResize(): this {
    this.cleanResize();
    this._resize$ = fromEvent(window, 'resize')
      .pipe(debounceTime(100))
      .subscribe(() => {
        this._editor!.layout();
        this.notifyEvent('resize');
      });
    return this;
  }
Example #25
Source File: page-visibility.ts    From common with MIT License 6 votes vote down vote up
PAGE_VISIBILITY = new InjectionToken<Observable<boolean>>(
    'Shared Observable based on `document visibility changed`',
    {
        factory: () => {
            const documentRef = inject(DOCUMENT);

            return fromEvent(documentRef, 'visibilitychange').pipe(
                startWith(0),
                map(() => documentRef.visibilityState !== 'hidden'),
                distinctUntilChanged(),
                share(),
            );
        },
    },
)
Example #26
Source File: editable.component.ts    From edit-in-place with MIT License 6 votes vote down vote up
private handleViewMode(): void {
    this.viewHandler = fromEvent(this.element, this.openBindingEvent)
      .pipe(
        filter(() => this.enabled),
        withLatestFrom(this.editMode$),
        filter(([_, editMode]) => !editMode),
        takeUntil(this.destroy$)
      )
      .subscribe(() => this.displayEditMode());
  }
Example #27
Source File: chat-bottom-bar.component.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
ngAfterViewInit() {
    this.ionContent.getScrollElement().then((element: HTMLElement) => {
      this.contentElement = element;
      this.contentClientHeight = element.clientHeight;
    });

    const drawerContainerElement = this.drawerContainer.nativeElement;

    fromEvent(drawerContainerElement, 'transitionend').pipe(
      takeUntil(this.destroyer),
      filter(({ target, propertyName }: TransitionEvent) => (
        target === drawerContainerElement && propertyName === 'height'
      ))
    ).subscribe(({ target }: TransitionEvent) => {
      const { clientHeight } = target as HTMLElement;

      // 如果抽屉打开了
      if (clientHeight > 0) {
        this.drawerClientHeight = clientHeight;
        this.ionContent.scrollByPoint(0, clientHeight, 50);
      } else {
        const { scrollHeight, scrollTop, clientHeight } = this.contentElement;
        // scrollHeight - scrollTop - clientHeight 得到距离底部的高度
        const canScroll = scrollHeight - scrollTop - clientHeight > this.drawerClientHeight;

        canScroll && this.ionContent.scrollByPoint(0, -this.drawerClientHeight, 50);
      }
    });
  }
Example #28
Source File: window.service.ts    From open-genes-frontend with Mozilla Public License 2.0 6 votes vote down vote up
constructor(@Inject(DOCUMENT) public document: Document) {
    this.windowWidth$ = fromEvent(window, 'resize').pipe(
      map(() => {
        const documentElement = document.documentElement;
        const bodyElement =
          document.body || document.getElementsByTagName('body')[0];
        return (
          window.innerWidth ||
          documentElement.clientWidth ||
          bodyElement.clientWidth
        );
      })
    );

    this.scroll$ = fromEvent(window, 'scroll').pipe(
      map(() => window.scrollY || this.document.documentElement.scrollTop)
    );
  }
Example #29
Source File: echarts.component.ts    From youpez-admin with MIT License 6 votes vote down vote up
ngOnInit() {
    this.resizeSub = fromEvent(window, 'resize').pipe(debounceTime(50)).subscribe(() => {
      if ((this.autoResize && window.innerWidth !== this.currentWindowWidth) || this.forceResize) {
        this.currentWindowWidth = window.innerWidth
        this.currentOffsetWidth = this.el.nativeElement.offsetWidth
        this.currentOffsetHeight = this.el.nativeElement.offsetHeight
        this.resize()
      }
    })
  }