UNPKG

@ashetm/ng-network

Version:

``@ashetm/ng-network`` is a library that provide some utilities classes, like pipes.

69 lines (62 loc) 3.06 kB
import * as i0 from '@angular/core'; import { inject, TemplateRef, ViewContainerRef, Directive } from '@angular/core'; import { fromEvent, merge, of, timer } from 'rxjs'; import { map, switchMap, startWith, retryWhen, delayWhen } from 'rxjs/operators'; const fromOfflineEvent = () => fromEvent(window, 'offline').pipe(map(() => void 0)); const fromOnlineEvent = () => fromEvent(window, 'online').pipe(map(() => void 0)); const fromNetworkEvents = () => merge(fromOfflineEvent().pipe(map(() => false)), fromOnlineEvent().pipe(map(() => true))); const fromNetworkLastTimeConnected = () => { const interval = 100; return fromNetworkEvents().pipe(switchMap((network) => network ? of(undefined) : timer(0, interval)), map((milliseconds) => milliseconds === undefined ? undefined : milliseconds * interval), startWith(undefined)); }; const fromNetworkStatus = () => { const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection; if (!connection) { return of(undefined); // Fallback when Network Information API is not supported } return fromEvent(connection, "change").pipe(startWith(connection), // Emit the initial state map(() => ({ effectiveType: connection.effectiveType || "unknown", downlink: connection.downlink || 0, rtt: connection.rtt || 0, saveData: connection.saveData || false, }))); }; /** * @requires NetworkModule */ class NetworkDirective { constructor() { this._templateRef = inject(TemplateRef); this._viewContainerRef = inject(ViewContainerRef); } ngAfterViewInit() { this._viewContainerRef.createEmbeddedView(this._templateRef, { $implicit: fromNetworkEvents(), lastTimeConnected$: fromNetworkLastTimeConnected() }); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.2.12", ngImport: i0, type: NetworkDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); } static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.2.12", type: NetworkDirective, selector: "ashetmNetwork", ngImport: i0 }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.2.12", ngImport: i0, type: NetworkDirective, decorators: [{ type: Directive, args: [{ selector: 'ashetmNetwork', standalone: false }] }] }); /** * @experimental feature */ function retryUntilOnline(durationStep = 1000, timeIncreasing = false) { return (source$) => source$.pipe(retryWhen((_) => fromNetworkEvents().pipe(delayWhen((isOnline, index) => isOnline ? source$ : timer((timeIncreasing ? index : 1) * durationStep))))); } /* * Public API Surface of network */ /** * Generated bundle index. Do not edit. */ export { NetworkDirective, fromNetworkEvents, fromNetworkLastTimeConnected, fromNetworkStatus, fromOfflineEvent, fromOnlineEvent, retryUntilOnline }; //# sourceMappingURL=ashetm-ng-network.mjs.map