Skip to content

Commit a13f805

Browse files
committed
feat(core): useBrowserOnly -> usePlatformOnly
1 parent 7b849d1 commit a13f805

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

packages/core/src/platform.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,48 @@
11
import { isPlatformBrowser } from '@angular/common';
22
import { inject, PLATFORM_ID } from '@angular/core';
33

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+
439
/**
540
* Dependency Assembler that assembles a function, which takes another function,
641
* invokes it and forwards its return value if within a browser environment, or
742
* return `null` otherwise.
843
*
44+
* @deprecated Prefer `usePlatformOnly`.
45+
*
946
* @example
1047
* ```ts
1148
* private browserOnly = useBrowserOnly();

0 commit comments

Comments
 (0)