|
1 | 1 | import { isPlatformBrowser } from '@angular/common'; |
2 | 2 | import { inject, PLATFORM_ID } from '@angular/core'; |
3 | 3 |
|
| 4 | +/** |
| 5 | + * Accepts a `PLATFORM_ID` value and returns a boolean value indicating whether |
| 6 | + * the current platform is expected. `isPlatformBrowser` and `isPlatformServer` |
| 7 | + * are all valid `PlatformSelector` functions. |
| 8 | + */ |
| 9 | +export interface PlatformSelector { |
| 10 | + (platformId: object): boolean; |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * Create a function that accepts another function. |
| 15 | + * If the current platform matches the given `PlatformSelector`, the accepted |
| 16 | + * function is invoked and its return value is forwarded. |
| 17 | + * Otherwise, `null` is returned. |
| 18 | + * |
| 19 | + * @example |
| 20 | + * ```ts |
| 21 | + * private onBrowser = usePlatformOnly(BROWSER); |
| 22 | + * ``` |
| 23 | + * ```ts |
| 24 | + * // href is `null` if not in a browser environment |
| 25 | + * const href = this.onBrowser(() => window.location.href); |
| 26 | + * ``` |
| 27 | + * ```ts |
| 28 | + * // alert is only invoked in a browser environment |
| 29 | + * this.onBrowser(() => alert('Hello, World!')); |
| 30 | + * ``` |
| 31 | + */ |
| 32 | +export const usePlatformOnly = |
| 33 | + (selector: PlatformSelector, platformId = inject(PLATFORM_ID)) => |
| 34 | + <Return>(fn: () => Return): Return | null => { |
| 35 | + if (!selector(platformId)) return null; |
| 36 | + return fn(); |
| 37 | + }; |
| 38 | + |
4 | 39 | /** |
5 | 40 | * Dependency Assembler that assembles a function, which takes another function, |
6 | 41 | * invokes it and forwards its return value if within a browser environment, or |
7 | 42 | * return `null` otherwise. |
8 | 43 | * |
| 44 | + * @deprecated Prefer `usePlatformOnly`. |
| 45 | + * |
9 | 46 | * @example |
10 | 47 | * ```ts |
11 | 48 | * private browserOnly = useBrowserOnly(); |
|
0 commit comments