rxjs#startWith TypeScript Examples

The following examples show how to use rxjs#startWith. 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: create-filter.component.ts    From worktez with MIT License 6 votes vote down vote up
readTeamData(teamId :string){
    this.enableLoader = true;
    this.appSettings.getTeamDetails(teamId).subscribe(team => {
          this.priorityLabels = team.Priority;
          this.statusLabels = team.Status;
          this.type = team.Type;
          this.difficultyLabels = team.Difficulty;
          this.teamMembers=team.TeamMembers;
          this.teamName=team.TeamName;
          this.sprintNumber = team.CurrentSprintId;
          this.currentSprintNumber=team.CurrentSprintId;
          this.backlogSprintNumber=-1;

          this.filteredOptionsAssignee = this.assigneeName.valueChanges.pipe(
            startWith(''),
            map((value) => {
              return this._filter(value)
            }),
          );

          this.filteredOptionsReporter = this.reporterName.valueChanges.pipe(
            startWith(''),
            map(value => this._filter(value)),
          );
          this.enableLoader = false;
    }); 
  }
Example #2
Source File: observables.tsx    From logseq-plugin-todo-master with MIT License 6 votes vote down vote up
change$ = new Observable<ChangeEvent>((sub) => {
  let destroyed = false;
  let listener = (changes: ChangeEvent) => {
    if (!destroyed) {
      sub.next(changes);
    }
  };
  // TODO: onChanged seems not return off hook
  const unsubscribe = logseq.DB.onChanged(listener);
  return () => {
    unsubscribe();
    destroyed = true;
  };
})
  .pipe(debounceTime(500))
  .pipe(startWith(null))
Example #3
Source File: auth.ts    From bext with MIT License 6 votes vote down vote up
octokit$
  .pipe(
    switchMap((octokit) =>
      octokit
        ? from(octokit.rest.users.getAuthenticated()).pipe(
            map(({ data, status }) =>
              status === 200
                ? ({ status: 'complete', user: data } as const)
                : ({ status: 'error' } as const),
            ),
            startWith({ status: 'loading' } as const),
            retry(2),
            catchError(() => of({ status: 'error' } as const)),
          )
        : of({ status: 'unauth' } as const),
    ),
  )
  .subscribe(user$);
Example #4
Source File: tree-select.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterViewInit() {
    const hasVisibleChildNodes$ = this.childNodes.changes.pipe(
      startWith(this.childNodes),
      switchMap((nodes: QueryList<TreeNodeComponent<T>>) =>
        nodes.length > 0
          ? combineLatest(nodes.map(node => node.visible$))
          : of([false]),
      ),
      map(visible => visible.some(Boolean)),
      tap(hasVisibleChildren => (this.isLeaf = !hasVisibleChildren)),
    );
    this.visible$ = combineLatest([
      this.selfVisible$,
      hasVisibleChildNodes$,
    ]).pipe(
      map(visible => visible.some(Boolean)),
      publishRef(),
    );

    this.visible$.pipe(takeUntil(this.destroy$$)).subscribe(visible => {
      this.visible = visible;
      this.cdr.markForCheck();
    });
    this.selected$.pipe(takeUntil(this.destroy$$)).subscribe(selected => {
      this.selected = selected;
      this.cdr.markForCheck();
    });

    if (this.selected) {
      requestAnimationFrame(() => {
        this.scrollToNode(this);
      });
    }
  }
Example #5
Source File: table-scroll.directive.ts    From alauda-ui with MIT License 6 votes vote down vote up
viewMutation() {
    merge(
      observeResizeOn(this.containerEl),
      fromEvent(this.containerEl, 'scroll'),
    )
      .pipe(startWith(null), takeUntil(this.destroy$$))
      .subscribe(() => {
        this.mutateVerticalScroll();
        this.mutateHorizontalScroll();
      });
  }
Example #6
Source File: option-group.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterContentInit() {
    this.hasVisibleOption$ = this.options.changes.pipe(
      startWith(this.options),
      switchMap((options: QueryList<OptionComponent<T>>) =>
        options.length > 0
          ? combineLatest(options.map(node => node.visible$))
          : of([false]),
      ),
      map(visible => visible.some(Boolean)),
      publishRef(),
    );
  }
Example #7
Source File: multi-select.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
override ngAfterViewInit() {
    super.ngAfterViewInit();
    this.selectAllStatus$ = combineLatest([
      this.allOptions$,
      this.filterString$,
    ]).pipe(
      switchMap(([allOptions]) =>
        combineLatest([
          ...(allOptions ?? [])
            .filter(({ visible, disabled }) => visible && !disabled)
            .map(({ selected$ }) => selected$),
        ]),
      ),
      map(statuses => {
        const selected = statuses.filter(Boolean);
        return selected.length === 0
          ? SelectAllStatus.Empty
          : selected.length !== statuses.length
          ? SelectAllStatus.Indeterminate
          : SelectAllStatus.Checked;
      }),
      startWith(SelectAllStatus.Empty),
      tap(selectAllStatus => (this.selectAllStatus = selectAllStatus)),
      publishRef(),
    );
    this.hasEnabledOptions$ = combineLatest([
      this.allOptions$,
      this.filterString$,
    ]).pipe(
      map(
        ([allOptions]) =>
          !!allOptions.filter(({ visible, disabled }) => visible && !disabled)
            .length,
      ),
    );
  }
Example #8
Source File: base-select.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterContentInit() {
    this.customCreatedOptions$ = combineLatest([
      this.values$,
      (
        this.contentOptions.changes as Observable<QueryList<OptionComponent<T>>>
      ).pipe(
        startWith(this.contentOptions),
        switchMap((options: QueryList<OptionComponent<T>>) =>
          options.length > 0
            ? combineLatest(options.map(option => option.value$))
            : of([] as T[]),
        ),
      ),
    ]).pipe(
      map(([values, optionValues]) =>
        values.reduce<Array<SelectFilterOption<T>>>((acc, value) => {
          const included = optionValues
            .map(value => this.trackFn(value))
            .includes(this.trackFn(value));
          if (!included) {
            const label =
              this.labelFn?.(value) || coerceString(this.trackFn(value));
            if (label) {
              acc.push({
                label,
                value,
              });
            }
          }
          return acc;
        }, []),
      ),
      publishRef(),
    );
  }
Example #9
Source File: form-item.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
mapControlStatus(control: NgControl) {
    return (
      this.parentForm
        ? combineLatest([
            control.statusChanges.pipe(startWith(control.status)),
            merge(
              this.parentForm.statusChanges.pipe(
                startWith(this.parentForm.status),
              ),
              this.parentForm.ngSubmit,
            ),
          ]).pipe(map(([status]: string[]) => status))
        : control.statusChanges
    ).pipe(
      map(
        (status: string) =>
          status === 'INVALID' && (control.dirty || this.parentForm?.submitted),
      ),
      publishRef(),
    );
  }
Example #10
Source File: form-item.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterContentInit() {
    this.hasError$ = this.ngControls.changes.pipe(
      startWith(this.ngControls),
      switchMap((controls: QueryList<NgControl>) =>
        combineLatest(
          controls.map(control => this.mapControlStatus(control)),
        ).pipe(map(statuses => statuses.some(Boolean))),
      ),
    );

    this.errorCount$ = this.errors.changes.pipe(
      map(errors => errors.length),
      startWith(this.errors.length),
    );

    this.hintCount$ = this.hints.changes.pipe(
      map(hints => hints.length),
      startWith(this.hints.length),
    );
  }
Example #11
Source File: accordion-item.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterContentInit() {
    if (this._lazyContentTpl) {
      // Render the content as soon as the accordion becomes open.
      this.opened
        .pipe(
          startWith(null as void),
          filter(() => !!this.expanded),
          take(1),
        )
        .subscribe(() => {
          this.lazyContentTpl = this._lazyContentTpl;
        });
    }
  }
Example #12
Source File: create-new-task.component.ts    From worktez with MIT License 6 votes vote down vote up
readTeamData(teamId :string){
    this.enableLoader = true;
    this.applicationSetting.getTeamDetails(teamId).subscribe(team => {
          this.priorityLabels = team.Priority;
          this.statusLabels = team.Status;
          this.type = team.Type;
          this.difficultyLabels = team.Difficulty;
          this.teamMembers=team.TeamMembers;
          this.teamName=team.TeamName;
          this.sprintNumber = team.CurrentSprintId;
          this.currentSprintNumber=team.CurrentSprintId;
          this.backlogSprintNumber=-1;

          this.filteredOptionsAssignee = this.assigneeName.valueChanges.pipe(
            startWith(''),
            map((value) => {
              return this._filter(value)
            }),
          );

          this.filteredOptionsReporter = this.reporterName.valueChanges.pipe(
            startWith(''),
            map(value => this._filter(value)),
          );
          this.enableLoader = false;
    }); 
  }
Example #13
Source File: edit-page.component.ts    From worktez with MIT License 6 votes vote down vote up
readTeamMembers(teamId :string){
    this.applicationSetting.getTeamDetails(teamId).subscribe(team => {
          this.teamMembers=team.TeamMembers;
          this.teamName=team.TeamName;
          this.currentSprintNumber=team.CurrentSprintId;
          this.backlogSprintNumber=-1;


          this.assigneeName.valueChanges.pipe(
            startWith(''),
            map((value) => {
              return this._filter(value)
            }),
          ).subscribe({
            next :(data) => {
              this.filteredOptionsAssignee = data
            },
            error:(error) => {
              console.error(error)
            },
            complete:() => console.info("Getting filtered options Assignee was successfull")
          });

          this.reporterName.valueChanges.pipe(
            startWith(''),
            map(value => this._filter(value)),
          ).subscribe({
            
            next :(data) => {
              this.filteredOptionsReporter = data
            },
            error:(error) => {
              console.error(error)
            },
            complete:() => console.info("Getting filtered options Assignee was successfull")
          });
    }); 
  }
Example #14
Source File: task-ecard.component.ts    From worktez with MIT License 6 votes vote down vote up
ngOnInit(): void {
    this.statusLabels = this.applicationSettingsService.status;
    this.priorityLabels = this.applicationSettingsService.priority;
    this.difficultyLabels = this.applicationSettingsService.difficulty;
    this.teamMembers = this.applicationSettingsService.team.TeamMembers;
    this.todayDate = this.toolsService.date();
    this.time = this.toolsService.time();

    this.filteredOptionsAssignee = this.assigneeName.valueChanges.pipe(
      startWith(''),
      map((value) => {
        return this._filter(value)
      }),
    );
  }
Example #15
Source File: suggestion-group.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterContentInit() {
    this.hasVisibleSuggestion$ = this.suggestions.changes.pipe(
      startWith(this.suggestions),
      switchMap((options: QueryList<SuggestionComponent>) =>
        options.length > 0
          ? combineLatest(options.map(node => node.visible$))
          : of([false]),
      ),
      map(visible => visible.some(Boolean)),
      publishRef(),
    );
  }
Example #16
Source File: anchor.directive.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterContentInit() {
    const containerEl = this.containerEl;
    this.anchorPortal = new ComponentPortal(AnchorComponent);
    const portalOutlet = new DomPortalOutlet(
      document.body,
      this.cfr,
      this.appRef,
      this.injector,
    );
    const anchorComponentRef = this.anchorPortal.attach(portalOutlet);
    const anchorEl = anchorComponentRef.injector.get(ElementRef)
      .nativeElement as HTMLElement;

    requestAnimationFrame(() =>
      this.adaptAnchorPosition(containerEl, anchorEl),
    );

    this.anchorLabels.changes
      .pipe(startWith(this.anchorLabels), takeUntil(this.destroy$$))
      .subscribe((anchorLabels: QueryList<AnchorLabelDirective>) => {
        Object.assign(anchorComponentRef.instance, {
          items: anchorLabels.toArray(),
        });
      });
  }
Example #17
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 #18
Source File: autocomplete.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterContentInit() {
    this.hasVisibleSuggestion$ = this.suggestions.changes.pipe(
      startWith(this.suggestions),
      switchMap((suggestions: QueryList<SuggestionComponent>) =>
        suggestions.length > 0
          ? combineLatest(suggestions.map(suggestion => suggestion.visible$))
          : of([] as boolean[]),
      ),
      map(visible => visible.some(Boolean)),
      withLatestFrom(this.directive$$),
      map(([hasVisibleSuggestion, directive]) => {
        if (hasVisibleSuggestion && directive.defaultFirstSuggestion) {
          directive.autoFocusFirstSuggestion();
        }
        return hasVisibleSuggestion;
      }),
      distinctUntilChanged(),
      debounceTime(0),
      tap(() => this.cdr.markForCheck()),
      publishRef(),
    );

    this.hasContent$ = combineLatest([
      this.hasVisibleSuggestion$,
      this.placeholder.changes.pipe(
        startWith(this.placeholder),
        map(
          (list: QueryList<AutocompletePlaceholderComponent>) => !!list.length,
        ),
      ),
    ]).pipe(
      map(
        ([hasVisibleSuggestion, hasPlaceholder]) =>
          hasVisibleSuggestion || hasPlaceholder,
      ),
    );
  }
Example #19
Source File: autocomplete.directive.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngOnInit() {
    this.show.subscribe(() => {
      this.updateSuggestionsContext();
    });
    this.hide.subscribe(() => {
      this.resetFocusedSuggestion();
    });

    if (this.ngControl) {
      this.ngControl.valueChanges
        .pipe(takeUntil(this.unsubscribe$))
        .subscribe((value: string | string[]) => {
          if (!Array.isArray(value)) {
            this.inputValue$$.next(value);
          }
        });

      this.ngControl.statusChanges
        .pipe(startWith(this.ngControl.status), takeUntil(this.unsubscribe$))
        .subscribe(status => {
          this.disabled = status === 'DISABLED';
        });
    }
  }
Example #20
Source File: multi-select.component.ts    From alauda-ui with MIT License 5 votes vote down vote up
override ngAfterContentInit() {
    super.ngAfterContentInit();

    this.selectedOptions$ = combineLatest([
      this.model$,
      (
        this.contentOptions.changes as Observable<QueryList<OptionComponent<T>>>
      ).pipe(
        startWith(this.contentOptions),
        switchMap((options: QueryList<OptionComponent<T>>) =>
          options.length > 0
            ? combineLatest(
                options.map(option =>
                  combineLatest([
                    option.value$,
                    option.label$,
                    option.labelContext$,
                    option.disabled$,
                  ]).pipe(
                    map(([value, label, labelContext, disabled]) => ({
                      value,
                      label,
                      labelContext,
                      disabled,
                    })),
                  ),
                ),
              )
            : of([] as Array<SelectFilterOption<T>>),
        ),
      ),
    ]).pipe(
      map(([values, options]) =>
        values
          .map(value => {
            const option = options.find(
              option => this.trackFn(option.value) === this.trackFn(value),
            );
            return option
              ? {
                  label:
                    option.label || coerceString(this.trackFn(option.value)),
                  labelContext: option.labelContext,
                  value: option.value,
                  disabled: option.disabled,
                }
              : {
                  label:
                    this.labelFn?.(value) || coerceString(this.trackFn(value)),
                  value,
                };
          })
          // sort disabled options as first
          .sort((a, b) => {
            if (a.disabled) {
              return -1;
            }

            if (b.disabled) {
              return 1;
            }

            return 0;
          }),
      ),
      publishRef(),
    );
  }
Example #21
Source File: select.component.ts    From alauda-ui with MIT License 5 votes vote down vote up
override ngAfterContentInit() {
    super.ngAfterContentInit();

    this.selectedOption$ = combineLatest([
      (
        this.contentOptions.changes as Observable<QueryList<OptionComponent<T>>>
      ).pipe(
        startWith(this.contentOptions),
        switchMap(options =>
          combineLatest(options.map(option => option.selected$)).pipe(
            startWith(null as void),
            map(() => options.find(option => option.selected)),
            distinctUntilChanged(),
            switchMap(option =>
              option
                ? combineLatest([
                    option.value$,
                    option.label$,
                    option.labelContext$,
                  ]).pipe(
                    map(([value, label, labelContext]) => ({
                      value,
                      label,
                      labelContext,
                    })),
                  )
                : of(null as void),
            ),
          ),
        ),
      ),
      this.model$,
    ]).pipe(
      map(([option, value]) =>
        option
          ? {
              label:
                option.label ||
                this.labelFn?.(option.value) ||
                coerceString(this.trackFn(option.value)),
              // https://github.com/angular/angular/issues/24515
              labelContext: {
                ...(option.labelContext as Record<string, unknown>),
              },
            }
          : {
              label: this.labelFn?.(value) || coerceString(this.trackFn(value)),
            },
      ),
      publishRef(),
    );

    this.hasSelected$ = this.selectedOption$.pipe(
      map(({ label }) => !!label),
      publishRef(),
    );
  }
Example #22
Source File: base-select.ts    From alauda-ui with MIT License 5 votes vote down vote up
ngAfterViewInit() {
    this.allOptions$ = combineLatest([
      this.customOptions.changes.pipe(startWith(this.customOptions)),
      this.contentOptions.changes.pipe(startWith(this.contentOptions)),
    ]).pipe(
      map(
        ([customOptions, contentOptions]: [
          QueryList<OptionComponent<T>>,
          QueryList<OptionComponent<T>>,
        ]) => [...customOptions.toArray(), ...contentOptions.toArray()],
      ),
      publishRef(),
    );

    // support dynamic options loading on filtering
    this.allOptions$.pipe(takeUntil(this.destroy$$)).subscribe(() => {
      if (this.opened) {
        requestAnimationFrame(() => {
          this.autoFocusFirstOption();
        });
      }
    });

    this.hasMatchedOption$ = combineLatest([
      this.allOptions$.pipe(
        map(customOptions =>
          customOptions.filter(option => option !== this.inputtingOption),
        ),
        // eslint-disable-next-line sonarjs/no-identical-functions
        switchMap(options =>
          options.length > 0
            ? combineLatest(options.map(option => option.value$))
            : of([] as T[]),
        ),
      ),
      this.filterString$,
    ]).pipe(
      map(([values, filterString]) =>
        values.some(value => this.trackFn(value) === filterString),
      ),
      publishRef(),
    );

    this.hasVisibleOption$ = (
      this.contentOptions.changes as Observable<QueryList<OptionComponent<T>>>
    ).pipe(
      startWith(this.contentOptions),
      switchMap((options: QueryList<OptionComponent<T>>) =>
        options.length > 0
          ? combineLatest(options.map(option => option.visible$))
          : of([] as boolean[]),
      ),
      map(visible => visible.some(Boolean)),
      publishRef(),
    );
  }
Example #23
Source File: toc-container.directive.ts    From alauda-ui with MIT License 5 votes vote down vote up
ngAfterContentInit() {
    const actived$ = this._scrollTop$
      .pipe(
        startWith(this.scrollTop),
        debounceTime(200),
        map(scrollTop =>
          this._contents.reduce(
            this.isScrollEnd
              ? this.getMaxContent.bind(this)
              : this.getMinContent(scrollTop),
          ),
        ),
        map(actived => actived.auiTocContent),
      )
      .pipe(
        tap(actived => {
          this._contents.forEach(content => {
            content.active = actived === content.auiTocContent;
          });
          this.cdr.detectChanges();
        }),
      );

    const scrollTween$ = this._scrollTo$.pipe(
      switchMap(name => {
        const target = this._contents.find(
          content => content.auiTocContent === name,
        );

        if (!target) {
          return EMPTY;
        }
        const destination = this.getOffsetTop(target.nativeElement);

        const start = performance.now();
        const source = this.scrollTop;
        const duration = 500;

        return of(0).pipe(
          observeOn(animationFrameScheduler),
          repeat(),
          map(() => (performance.now() - start) / duration),
          takeWhile(t => t < 1),
          endWith(1),
          map(t => t * t * t),
          map(t => source * (1 - t) + destination * t),
        );
      }),
      takeUntil(this._onDestroy$),
    );

    this._subs.push(
      actived$.subscribe(this.activedChange),
      scrollTween$.subscribe(tweenValue => {
        this.scrollTop = tweenValue;
      }),
    );
  }
Example #24
Source File: tooltip.component.ts    From alauda-ui with MIT License 5 votes vote down vote up
setupInputs(inputs: {
    inputContent$: Observable<string | TemplateRef<any>>;
    inputType$: Observable<TooltipType>;
    inputPosition$: Observable<string>;
    inputClass$: Observable<string>;
    inputContext$: Observable<any>;
  }) {
    Object.assign(this, inputs);
    this.text$ = this.inputContent$.pipe(
      map(val => {
        if (typeof val === 'string') {
          return val;
        }
        return '';
      }),
      publishRef(),
    );
    this.template$ = this.inputContent$.pipe(
      map(val => {
        if (typeof val !== 'string') {
          return val;
        }
        return null;
      }),
      publishRef(),
    );
    this.class$ = combineLatest([
      this.inputPosition$.pipe(startWith('top')),
      this.inputType$.pipe(startWith(TooltipType.Default)),
      this.inputClass$.pipe(startWith('')),
    ]).pipe(
      map(([inputPosition, inputType, inputClass]) => {
        const b = this.bem.block();
        const dir = inputPosition.split(' ')[0];
        return inputType === TooltipType.Plain
          ? `${b}--${dir} ${inputClass}`
          : `${b} ${b}--${inputType} ${b}--${dir} ${inputClass}`;
      }),
      publishRef(),
    );
    this.context$ = this.inputContext$.pipe(publishRef());
  }
Example #25
Source File: watch-content-exist.ts    From alauda-ui with MIT License 5 votes vote down vote up
export function watchContentExist(queryList: QueryList<unknown>) {
  return queryList.changes.pipe(
    startWith(queryList),
    map((list: QueryList<unknown>) => !!list.length),
    publishRef(),
  );
}
Example #26
Source File: publish-list.tsx    From bext with MIT License 5 votes vote down vote up
PublishList: FC = () => (
  <div className="py-3">
    {useObservableState(
      useObservable(() =>
        user$.pipe(
          switchMap(({ status, user }) => {
            switch (status) {
              case 'loading':
                return of(<Spinner />);
              case 'complete':
                const octokit = octokit$.getValue()!;
                return timer(0, REFRESH_DURATION).pipe(
                  switchMap(() =>
                    from(
                      octokit.paginate(octokit.search.issuesAndPullRequests, {
                        q: `is:pr author:${user?.login} repo:${packageJson.metaRepository.owner}/${packageJson.metaRepository.repo}`,
                        sort: 'created',
                        order: 'desc',
                      }),
                    ).pipe(
                      map((items) => (
                        <>
                          <Banner current={Date.now()} empty={!items.length} />
                          {items.length ? (
                            <List
                              items={items}
                              onRenderCell={(item) => <PrItem item={item!} />}
                            />
                          ) : null}
                        </>
                      )),
                      retry(2),
                      catchError(() =>
                        of(<div className="text-center">出错了...</div>),
                      ),
                    ),
                  ),
                );
              default:
                return of(
                  <div className="text-center">
                    <LoginLink /> 后查看发布历史
                  </div>,
                );
            }
          }),
          startWith(<Spinner />),
        ),
      ),
    ) || null}
  </div>
)
Example #27
Source File: autosize.directive.ts    From alauda-ui with MIT License 5 votes vote down vote up
ngAfterViewInit() {
    this.ngControl.valueChanges
      .pipe(startWith(null as void), takeUntil(this.destroy$$))
      .subscribe(() => this.resizeTextarea());
  }
Example #28
Source File: github-login.tsx    From bext with MIT License 4 votes vote down vote up
GithubLogin: FC = () => {
  const [{ code }] = useUrlState({ code: undefined });
  const historyReplace = useHistoryReplace();
  const { notify, dismissNotification } = useNotifications();

  useRequest(
    async () => {
      const id = uniqueId('login-loading');
      notify({
        id,
        status: 'loading',
        message: '登录中',
        dismissAfter: 0,
        dismissible: false,
      });
      const response = await fetch(`/api/gh/login?code=${code}`);
      const data = await response.json();
      if (
        response.ok &&
        data.code === 200 &&
        typeof data?.data?.access_token === 'string'
      ) {
        accessToken$.next(data.data.access_token);
        notify({
          status: 'success',
          message: '登录成功',
        });
        historyReplace(location.pathname);
        trackEvent(Events.ghLoginSuccess);
      } else {
        notify({
          status: 'error',
          message:
            data?.data?.error_description || data?.msg || response.statusText,
        });
      }
      dismissNotification(id);
    },
    {
      ready: !!code,
      refreshDeps: [code],
      onError: () => notify({ status: 'error', message: '登录失败' }),
    },
  );

  const el = useObservableState(
    useObservable(() =>
      octokit$.pipe(
        switchMap((octokit) =>
          octokit
            ? user$.pipe(
                map(({ status, user }) => {
                  switch (status) {
                    case 'complete':
                      return (
                        <div className="flex justify-between">
                          <Persona
                            imageUrl={user?.avatar_url}
                            text={user?.name || user?.login}
                            secondaryText={user?.bio || '暂无签名'}
                          />
                          <Link onClick={() => accessToken$.next(undefined)}>
                            退出
                          </Link>
                        </div>
                      );
                    case 'loading':
                      return '获取用户信息...';
                    default:
                      return (
                        <>
                          发布、更新脚本请先
                          <LoginLink />
                        </>
                      );
                  }
                }),
                startWith('获取用户信息...'),
              )
            : of(
                <>
                  发布、更新脚本请先
                  <LoginLink />
                </>,
              ),
        ),
      ),
    ),
    null,
  );

  return (
    <>
      <Title>Github</Title>
      {el}
    </>
  );
}