|
| 1 | +import {inject, NgZone, Provider, Type} from '@angular/core'; |
| 2 | +import type {SwPush} from '@angular/service-worker'; |
| 3 | +import {ANIMATION_FRAME, SERVICE_WORKER, zoneOptimized} from '@ng-web-apis/common'; |
| 4 | +import {combineLatest, filter, from, map, NEVER, pairwise, share, switchMap} from 'rxjs'; |
| 5 | +import {NOTIFICATION_SW_CLICKS} from '../tokens/notification-clicks'; |
| 6 | +import {NOTIFICATION_SW_CLOSES} from '../tokens/notification-closes'; |
| 7 | + |
| 8 | +export function provideSwPush(swPush: Type<SwPush>): Provider[] { |
| 9 | + return [ |
| 10 | + { |
| 11 | + provide: NOTIFICATION_SW_CLICKS, |
| 12 | + deps: [swPush], |
| 13 | + useFactory: ({isEnabled, notificationClicks}: SwPush) => |
| 14 | + isEnabled ? notificationClicks : NEVER, |
| 15 | + }, |
| 16 | + { |
| 17 | + provide: NOTIFICATION_SW_CLOSES, |
| 18 | + /** |
| 19 | + * TODO: refactor the token's factory after this issue will be solved: |
| 20 | + * https://github.com/angular/angular/issues/52244 |
| 21 | + * ``` |
| 22 | + * { |
| 23 | + * provide: NOTIFICATION_SW_CLOSES, |
| 24 | + * useValue: swPush.isEnabled ? swPush.notificationCloses : NEVER, |
| 25 | + * }, |
| 26 | + * ``` |
| 27 | + */ |
| 28 | + useFactory: () => |
| 29 | + combineLatest([ |
| 30 | + from(inject(SERVICE_WORKER).getRegistration()), |
| 31 | + inject(ANIMATION_FRAME), |
| 32 | + ]).pipe( |
| 33 | + switchMap(([reg]) => (reg ? from(reg.getNotifications()) : NEVER)), |
| 34 | + pairwise(), |
| 35 | + filter(([prev, cur]) => prev.length > cur.length), |
| 36 | + map( |
| 37 | + ([prev, cur]) => |
| 38 | + prev.find((notification, i) => notification !== cur[i])!, |
| 39 | + ), |
| 40 | + zoneOptimized(inject(NgZone)), |
| 41 | + share(), |
| 42 | + ), |
| 43 | + }, |
| 44 | + ]; |
| 45 | +} |
0 commit comments