rxjs#identity TypeScript Examples

The following examples show how to use rxjs#identity. 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: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
/* ----------------------------------------------------------------------------
 * Functions
 * ------------------------------------------------------------------------- */

/**
 * Resolve a pattern
 *
 * @param pattern - Pattern
 * @param options - Options
 *
 * @returns File observable
 */
export function resolve(
  pattern: string, options?: ResolveOptions
): Observable<string> {
  return from(glob(pattern, options))
    .pipe(
      catchError(() => EMPTY),
      switchMap(files => from(files)),
      options?.watch
        ? mergeWith(watch(pattern, options))
        : identity
    )
}
Example #2
Source File: index.ts    From dbm with Apache License 2.0 6 votes vote down vote up
/**
 * Write a file, but only if the contents changed
 *
 * @param file - File
 * @param data - File data
 *
 * @returns File observable
 */
export function write(file: string, data: string): Observable<string> {
  let contents = cache.get(file)
  if (contents === data) {
    return of(file)
  } else {
    cache.set(file, data)
    return defer(() => fs.writeFile(file, data))
      .pipe(
        mapTo(file),
        process.argv.includes("--verbose")
          ? tap(file => console.log(`${now()} + ${file}`))
          : identity
      )
  }
}
Example #3
Source File: activator-installer.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
/**
   * Creates a Promise that resolves when given activators signal ready.
   */
  private async waitForActivatorsToSignalReady(appSymbolicName: string, activators: Activator[], monitor: ProgressMonitor): Promise<void> {
    const t0 = Date.now();
    const activatorLoadTimeout = Beans.get(ApplicationRegistry).getApplication(appSymbolicName)!.activatorLoadTimeout;
    const readinessPromises: Promise<void>[] = activators
      .reduce((acc, activator) => acc.concat(Arrays.coerce(activator.properties.readinessTopics)), new Array<string>()) // concat readiness topics
      .map(readinessTopic => {
          const onReadinessTimeout = (): Observable<never> => {
            Beans.get(Logger).error(`[ActivatorLoadTimeoutError] Timeout elapsed while waiting for application to signal readiness [app=${appSymbolicName}, timeout=${activatorLoadTimeout}ms, readinessTopic=${readinessTopic}].`);
            return EMPTY;
          };
          return new Promise((resolve, reject) => {
            return Beans.get(MessageClient).observe$<void>(readinessTopic)
              .pipe(
                first(msg => msg.headers.get(MessageHeaders.AppSymbolicName) === appSymbolicName),
                activatorLoadTimeout ? timeout({first: activatorLoadTimeout, with: onReadinessTimeout}) : identity,
              )
              .subscribe({
                error: reject,
                complete: resolve,
              });
          });
        },
      );

    if (!readinessPromises.length) {
      monitor.done();
      return;
    }

    await Promise.all(readinessPromises);
    monitor.done();
    Beans.get(Logger).info(`Activator startup of '${appSymbolicName}' took ${Date.now() - t0}ms.`);
  }
Example #4
Source File: manifest-collector.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
private async fetchAndRegisterManifest(appConfig: ApplicationConfig, monitor: ProgressMonitor): Promise<void> {
    try {
      if (!appConfig.manifestUrl) {
        Beans.get(Logger).error(`[AppConfigError] Failed to fetch manifest for application '${appConfig.symbolicName}'. Manifest URL must not be empty.`);
        return;
      }

      const fetchManifest$ = from(Beans.get(HttpClient).fetch(appConfig.manifestUrl));
      const manifestFetchTimeout = appConfig.manifestLoadTimeout ?? Beans.get(MicrofrontendPlatformConfig).manifestLoadTimeout;
      const onManifestFetchTimeout = (): Observable<never> => throwError(() => `Timeout of ${manifestFetchTimeout}ms elapsed.`);
      const manifestFetchResponse = await firstValueFrom(fetchManifest$.pipe(manifestFetchTimeout ? timeout({first: manifestFetchTimeout, with: onManifestFetchTimeout}) : identity));

      if (!manifestFetchResponse.ok) {
        Beans.get(Logger).error(`[ManifestFetchError] Failed to fetch manifest for application '${appConfig.symbolicName}'. Maybe the application is currently unavailable. [httpStatusCode=${manifestFetchResponse.status}, httpStatusText=${manifestFetchResponse.statusText}]`, appConfig, manifestFetchResponse.status);
        return;
      }

      const manifest: Manifest = await manifestFetchResponse.json();

      // Let the host manifest be intercepted before registering it in the platform, for example by libraries integrating the SCION Microfrontend Platform, e.g., to allow the programmatic registration of capabilities or intentions.
      if (appConfig.symbolicName === Beans.get<string>(APP_IDENTITY)) {
        Beans.all(HostManifestInterceptor).forEach(interceptor => interceptor.intercept(manifest));
      }

      Beans.get(ApplicationRegistry).registerApplication(appConfig, manifest);
      Beans.get(Logger).info(`Registered application '${appConfig.symbolicName}' in the SCION Microfrontend Platform.`);
    }
    catch (error) {
      // The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500.
      // It will only reject on network failure or if anything prevented the request from completing.
      // See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful
      Beans.get(Logger).error(`[ManifestFetchError] Failed to fetch manifest for application '${appConfig.symbolicName}'. Maybe the application is currently unavailable.`, error);
    }
    finally {
      monitor.done();
    }
  }
Example #5
Source File: test.spec.ts    From ng-event-plugins with Apache License 2.0 4 votes vote down vote up
describe('EventManagers', () => {
    @Component({
        template: `
            <div class="wrapper" (click)="onWrapper($event)">
                <div
                    id="stopped-clicks"
                    class="element"
                    (click.stop)="onStoppedClick()"
                ></div>
                <div
                    id="prevented-clicks"
                    class="element"
                    (click.prevent)="onPreventedClick()"
                ></div>
                <div
                    id="filtered-clicks"
                    class="element"
                    (click.silent)="onFilteredClicks($event.bubbles)"
                ></div>
            </div>
            <div class="wrapper" (click.capture.stop)="(0)">
                <div id="captured-clicks" class="element" (click)="onCaptured()"></div>
            </div>
            <div class="wrapper" (click.self)="onBubbled()">
                <div id="bubbled-clicks" class="element" (click)="(0)"></div>
            </div>
        `,
        changeDetection: ChangeDetectionStrategy.OnPush,
    })
    class TestComponent {
        flag = false;
        onStoppedClick = jasmine.createSpy('onStoppedClick');
        onPreventedClick = jasmine.createSpy('onPreventedClick');
        onWrapper = jasmine.createSpy('onWrapper');
        onCaptured = jasmine.createSpy('onCaptured');
        onBubbled = jasmine.createSpy('onBubbled');

        @HostBinding('$.data-value.attr')
        @HostListener('$.data-value.attr')
        @HostBinding('$.tabIndex')
        @HostListener('$.tabIndex')
        @HostBinding('$.style.marginTop.%')
        @HostListener('$.style.marginTop.%')
        @HostBinding('$.class.active')
        @HostListener('$.class.active')
        readonly test = asCallable(new BehaviorSubject<number | null>(1));

        constructor(@Inject(ElementRef) readonly elementRef: ElementRef<HTMLElement>) {}

        @shouldCall(bubbles => bubbles)
        @HostListener('click.init', ['$event'])
        @HostListener('document:click.silent.stop.prevent')
        @HostListener('document:click.init')
        onFilteredClicks(_bubbles: boolean) {
            this.flag = true;
        }
    }

    @Component({
        template: `<div (document:click.capture)="(0)"></div>`,
        changeDetection: ChangeDetectionStrategy.OnPush,
    })
    class BrokenComponent {}

    let fixture: ComponentFixture<TestComponent>;
    let testComponent: TestComponent;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [EventPluginsModule],
            declarations: [TestComponent, BrokenComponent],
        });

        fixture = TestBed.createComponent(TestComponent);
        testComponent = fixture.componentInstance;
        fixture.detectChanges();
    });

    beforeEach(() => {
        testComponent.onWrapper.calls.reset();
        testComponent.onStoppedClick.calls.reset();
        testComponent.onPreventedClick.calls.reset();
        testComponent.onBubbled.calls.reset();
    });

    it('Clicks are stopped', () => {
        const event = new Event('click', {bubbles: true});
        const element = fixture.debugElement.query(By.css('#stopped-clicks'))!
            .nativeElement;

        element.dispatchEvent(event);
        fixture.detectChanges();

        expect(testComponent.onWrapper).not.toHaveBeenCalled();
        expect(testComponent.onStoppedClick).toHaveBeenCalled();
    });

    it('Clicks go through with default prevented', () => {
        const event = new Event('click', {bubbles: true, cancelable: true});
        const element = fixture.debugElement.query(By.css('#prevented-clicks'))!
            .nativeElement;

        element.dispatchEvent(event);
        fixture.detectChanges();

        expect(testComponent.onPreventedClick).toHaveBeenCalled();
        expect(testComponent.onWrapper).toHaveBeenCalled();
        expect(testComponent.onWrapper.calls.mostRecent().args[0].defaultPrevented).toBe(
            true,
        );
    });

    it('Clicks are filtered', () => {
        const event = new Event('click');
        const element = fixture.debugElement.query(By.css('#filtered-clicks'))!
            .nativeElement;

        element.dispatchEvent(event);
        fixture.detectChanges();

        expect(testComponent.flag).toBe(false);
    });

    it('Clicks go through filtered', () => {
        const event = new Event('click', {bubbles: true});
        const element = fixture.debugElement.query(By.css('#filtered-clicks'))!
            .nativeElement;

        element.dispatchEvent(event);
        fixture.detectChanges();

        expect(testComponent.flag).toBe(true);
    });

    it('Clicks are captured', () => {
        const event = new Event('click', {bubbles: true});
        const element = fixture.debugElement.query(By.css('#captured-clicks'))!
            .nativeElement;

        element.dispatchEvent(event);
        fixture.detectChanges();

        expect(testComponent.onCaptured).not.toHaveBeenCalled();
    });

    it('Self listeners not triggered on bubbled events', () => {
        const event = new Event('click', {bubbles: true});
        const element = fixture.debugElement.query(By.css('#bubbled-clicks'))!
            .nativeElement;

        element.dispatchEvent(event);
        fixture.detectChanges();

        expect(testComponent.onBubbled).not.toHaveBeenCalled();
    });

    it('Self listeners triggered on events originated on the same element', () => {
        const event = new Event('click', {bubbles: true});
        const element = fixture.debugElement.query(By.css('#bubbled-clicks'))!
            .nativeElement.parentElement;

        element.dispatchEvent(event);
        fixture.detectChanges();

        expect(testComponent.onBubbled).toHaveBeenCalled();
    });

    it('Global capture throws', () => {
        expect(() => {
            TestBed.createComponent(BrokenComponent).detectChanges();
        }).toThrow();
    });

    it('Observable bindings work', () => {
        expect(testComponent.elementRef.nativeElement.getAttribute('data-value')).toBe(
            '1',
        );
        expect(testComponent.elementRef.nativeElement.tabIndex).toBe(1);
        expect(testComponent.elementRef.nativeElement.style.marginTop).toBe('1%');
        expect(testComponent.elementRef.nativeElement.classList.contains('active')).toBe(
            true,
        );
    });

    it('Observable bindings are updated', () => {
        testComponent.test.next(null);

        expect(testComponent.elementRef.nativeElement.getAttribute('data-value')).toBe(
            null,
        );
        expect(testComponent.elementRef.nativeElement.tabIndex).toBe(0);
        expect(testComponent.elementRef.nativeElement.style.marginTop).toBe('1%');
        expect(testComponent.elementRef.nativeElement.classList.contains('active')).toBe(
            false,
        );
    });

    it('bind plugin doesnt crash if observable is missing', () => {
        const bind = new BindEventPlugin();
        const element: any = document.createElement('div');

        bind.manager = TestBed.inject(EventManager);

        expect(() => bind.addEventListener(element, 'test')).not.toThrow();
    });

    describe('shouldCall does not crash without zone', () => {
        class Test {
            flag = false;

            @shouldCall(identity)
            test(flag: boolean) {
                this.flag = flag;
            }
        }

        it('and calls the method', () => {
            const test = new Test();

            test.test(true);

            expect(test.flag).toBe(true);
        });

        it('and doesnt call the method', () => {
            const test = new Test();

            test.flag = true;
            test.test(false);

            expect(test.flag).toBe(true);
        });
    });
});
Example #6
Source File: data-report.stories.tsx    From ali-react-table with MIT License 4 votes vote down vote up
export function 典型数据报表() {
  const indicatorTree: ArtColumn[] = [
    {
      name: 'APP指标',
      code: 'app_qty_pbt',
      render: String,
      children: [
        { code: 'imp_uv_dau_pct', name: '曝光UV占DAU比例', render: ratio },
        {
          code: 'all_app_trd_amt_1d',
          name: 'APP成交金额汇总',
          render(value: any, record: any, recordIndex: number) {
            return amount(value)
          },
          getCellProps(value: any, record: any, recordIndex: number) {
            if (value > 30) {
              return { style: { color: 'red' } }
            }
          },
        },
        { code: 'app_trd_usr_cnt_1d', name: 'APP成交用户数', render: amount },
      ],
    },
    {
      name: '转换率',
      code: 'all_imp2pay_rate',
      render: ratio,
      children: [
        { code: 'all_imp2pay_rate', name: '整体曝光至成交转化率', render: ratio },
        { code: 'search_imp2pay_rate', name: '搜索曝光至成交转化率', render: ratio },
        { code: 'classis_imp2pay_rate', name: '分类曝光至成交转化率', render: ratio },
        { code: 'cart_imp2pay_rate', name: '购物车曝光至成交转化率', render: ratio },
      ],
    },
  ]

  const mainCol: ArtColumn = {
    name: '指标',
    width: 200,
    lock: true,
    render(value: any, record: any, recordIndex: number) {
      return record.name
    },
  }

  const [state, setState] = useState({
    isLoading: true,
    columns: [] as ArtColumn[],
  })

  useEffect(() => {
    getAppTrafficData().then((data) => {
      const codes = ['city_name', 'shop_name']
      const topTree = buildDrillTree(data, codes)
      const recordMap = buildRecordMap({ data, codes })

      // 动态生成表格列
      const columns = convertDrillTreeToColumns(recordMap, topTree)
      setState({ isLoading: false, columns })
    })
  }, [])

  const [openKeys, onChangeOpenKeys] = useState(['APP指标', '转换率'])

  const pipeline = useTablePipeline()
    .input({ columns: [mainCol, ...state.columns], dataSource: indicatorTree })
    .primaryKey('name')
    .use(
      features.treeMode({
        openKeys,
        onChangeOpenKeys,
        indentSize: 20,
      }),
    )

  return <WebsiteBaseTable {...pipeline.getProps()} isLoading={state.isLoading} />

  function convertDrillTreeToColumns(recordMap: Map<string, any>, nodes: DrillNode[]): ArtColumn[] {
    const result: ArtColumn[] = []
    for (const node of nodes) {
      result.push({
        name: node.value,
        code: node.key,
        render(_v, { code, render }) {
          const record = recordMap.get(node.key)
          return (render ?? identity)(record?.[code])
        },
        getCellProps(_v, { code, getCellProps }) {
          const record = recordMap.get(node.key)
          if (getCellProps != null) {
            return getCellProps(record?.[code])
          }
        },
        width: 150,
        children: isLeafNode(node) ? null : convertDrillTreeToColumns(recordMap, node.children),
      })
    }
    return result
  }
}
Example #7
Source File: actions.ts    From grafana-chinese with Apache License 2.0 4 votes vote down vote up
runQueries = (exploreId: ExploreId): ThunkResult<void> => {
  return (dispatch, getState) => {
    dispatch(updateTime({ exploreId }));

    const richHistory = getState().explore.richHistory;
    const exploreItemState = getState().explore[exploreId];
    const {
      datasourceInstance,
      queries,
      containerWidth,
      isLive: live,
      range,
      scanning,
      queryResponse,
      querySubscription,
      history,
      mode,
      showingGraph,
      showingTable,
    } = exploreItemState;

    if (!hasNonEmptyQuery(queries)) {
      dispatch(clearQueriesAction({ exploreId }));
      dispatch(stateSave()); // Remember to save to state and update location
      return;
    }

    // Some datasource's query builders allow per-query interval limits,
    // but we're using the datasource interval limit for now
    const minInterval = datasourceInstance.interval;

    stopQueryState(querySubscription);

    const datasourceId = datasourceInstance.meta.id;

    const queryOptions: QueryOptions = {
      minInterval,
      // maxDataPoints is used in:
      // Loki - used for logs streaming for buffer size, with undefined it falls back to datasource config if it supports that.
      // Elastic - limits the number of datapoints for the counts query and for logs it has hardcoded limit.
      // Influx - used to correctly display logs in graph
      maxDataPoints: mode === ExploreMode.Logs && datasourceId === 'loki' ? undefined : containerWidth,
      liveStreaming: live,
      showingGraph,
      showingTable,
      mode,
    };

    const datasourceName = exploreItemState.requestedDatasourceName;

    const transaction = buildQueryTransaction(queries, queryOptions, range, scanning);

    let firstResponse = true;

    const newQuerySub = runRequest(datasourceInstance, transaction.request)
      .pipe(
        // Simple throttle for live tailing, in case of > 1000 rows per interval we spend about 200ms on processing and
        // rendering. In case this is optimized this can be tweaked, but also it should be only as fast as user
        // actually can see what is happening.
        live ? throttleTime(500) : identity,
        map((data: PanelData) => preProcessPanelData(data, queryResponse))
      )
      .subscribe((data: PanelData) => {
        if (!data.error && firstResponse) {
          // Side-effect: Saving history in localstorage
          const nextHistory = updateHistory(history, datasourceId, queries);
          const arrayOfStringifiedQueries = queries.map(query =>
            datasourceInstance?.getQueryDisplayText
              ? datasourceInstance.getQueryDisplayText(query)
              : getQueryDisplayText(query)
          );

          const nextRichHistory = addToRichHistory(
            richHistory || [],
            datasourceId,
            datasourceName,
            arrayOfStringifiedQueries,
            false,
            '',
            ''
          );
          dispatch(historyUpdatedAction({ exploreId, history: nextHistory }));
          dispatch(richHistoryUpdatedAction({ richHistory: nextRichHistory }));

          // We save queries to the URL here so that only successfully run queries change the URL.
          dispatch(stateSave());
        }

        firstResponse = false;

        dispatch(queryStreamUpdatedAction({ exploreId, response: data }));

        // Keep scanning for results if this was the last scanning transaction
        if (getState().explore[exploreId].scanning) {
          if (data.state === LoadingState.Done && data.series.length === 0) {
            const range = getShiftedTimeRange(-1, getState().explore[exploreId].range);
            dispatch(updateTime({ exploreId, absoluteRange: range }));
            dispatch(runQueries(exploreId));
          } else {
            // We can stop scanning if we have a result
            dispatch(scanStopAction({ exploreId }));
          }
        }
      });

    dispatch(queryStoreSubscriptionAction({ exploreId, querySubscription: newQuerySub }));
  };
}