Skip to content

Commit 7c48500

Browse files
authored
refactor(platform): isPlatform() does not need window (ionic-team#19022)
1 parent e4357f9 commit 7c48500

File tree

2 files changed

+24
-8
lines changed

2 files changed

+24
-8
lines changed

core/src/utils/platform.ts

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,38 @@
11

22
export type Platforms = keyof typeof PLATFORMS_MAP;
33

4-
export const getPlatforms = (win: any) => setupPlatforms(win);
4+
interface IsPlatformSignature {
5+
(plt: Platforms): boolean;
6+
(win: Window, plt: Platforms): boolean;
7+
}
58

6-
export const isPlatform = (win: Window, platform: Platforms) =>
7-
getPlatforms(win).indexOf(platform) > -1;
9+
export const getPlatforms = (win?: any) => setupPlatforms(win);
810

9-
export const setupPlatforms = (win: any) => {
11+
export const isPlatform: IsPlatformSignature = (winOrPlatform: Window | Platforms | undefined, platform?: Platforms) => {
12+
if (typeof winOrPlatform === 'string') {
13+
platform = winOrPlatform;
14+
winOrPlatform = undefined;
15+
}
16+
return getPlatforms(winOrPlatform).includes(platform!);
17+
};
18+
19+
export const setupPlatforms = (win: any = window) => {
1020
win.Ionic = win.Ionic || {};
1121

12-
let platforms: string[] | undefined | null = win.Ionic.platforms;
22+
let platforms: Platforms[] | undefined | null = win.Ionic.platforms;
1323
if (platforms == null) {
1424
platforms = win.Ionic.platforms = detectPlatforms(win);
1525
platforms.forEach(p => win.document.documentElement.classList.add(`plt-${p}`));
1626
}
1727
return platforms;
1828
};
1929

30+
const detectPlatforms = (win: Window) =>
31+
(Object.keys(PLATFORMS_MAP) as Platforms[]).filter(p => PLATFORMS_MAP[p](win));
32+
2033
const isMobileWeb = (win: Window): boolean =>
2134
isMobile(win) && !isHybrid(win);
2235

23-
const detectPlatforms = (win: Window): string[] =>
24-
Object.keys(PLATFORMS_MAP).filter(p => (PLATFORMS_MAP as any)[p](win));
25-
2636
const isIpad = (win: Window) =>
2737
testUserAgent(win, /iPad/i);
2838

core/src/utils/test/platform.spec.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,12 @@ describe('Platform Tests', () => {
5151
expect(isPlatform(win, 'hybrid')).toEqual(true);
5252
});
5353

54+
it('should work without win parameter', () => {
55+
(global as any).window = configureBrowser(PlatformConfiguration.DesktopSafari);
56+
expect(isPlatform('capacitor')).toEqual(false);
57+
expect(isPlatform('desktop')).toEqual(true);
58+
});
59+
5460
it('should return false for "capacitor" and true for "desktop" on desktop safari', () => {
5561
const win = configureBrowser(PlatformConfiguration.DesktopSafari);
5662
expect(isPlatform(win, 'capacitor')).toEqual(false);

0 commit comments

Comments
 (0)