diff --git a/core/src/utils/platform.ts b/core/src/utils/platform.ts index b1465fd5a4..a6c2d7457d 100644 --- a/core/src/utils/platform.ts +++ b/core/src/utils/platform.ts @@ -1,15 +1,25 @@ export type Platforms = keyof typeof PLATFORMS_MAP; -export const getPlatforms = (win: any) => setupPlatforms(win); +interface IsPlatformSignature { + (plt: Platforms): boolean; + (win: Window, plt: Platforms): boolean; +} -export const isPlatform = (win: Window, platform: Platforms) => - getPlatforms(win).indexOf(platform) > -1; +export const getPlatforms = (win?: any) => setupPlatforms(win); -export const setupPlatforms = (win: any) => { +export const isPlatform: IsPlatformSignature = (winOrPlatform: Window | Platforms | undefined, platform?: Platforms) => { + if (typeof winOrPlatform === 'string') { + platform = winOrPlatform; + winOrPlatform = undefined; + } + return getPlatforms(winOrPlatform).includes(platform!); +}; + +export const setupPlatforms = (win: any = window) => { win.Ionic = win.Ionic || {}; - let platforms: string[] | undefined | null = win.Ionic.platforms; + let platforms: Platforms[] | undefined | null = win.Ionic.platforms; if (platforms == null) { platforms = win.Ionic.platforms = detectPlatforms(win); platforms.forEach(p => win.document.documentElement.classList.add(`plt-${p}`)); @@ -17,12 +27,12 @@ export const setupPlatforms = (win: any) => { return platforms; }; +const detectPlatforms = (win: Window) => + (Object.keys(PLATFORMS_MAP) as Platforms[]).filter(p => PLATFORMS_MAP[p](win)); + const isMobileWeb = (win: Window): boolean => isMobile(win) && !isHybrid(win); -const detectPlatforms = (win: Window): string[] => - Object.keys(PLATFORMS_MAP).filter(p => (PLATFORMS_MAP as any)[p](win)); - const isIpad = (win: Window) => testUserAgent(win, /iPad/i); diff --git a/core/src/utils/test/platform.spec.ts b/core/src/utils/test/platform.spec.ts index 51436075d0..484262224d 100644 --- a/core/src/utils/test/platform.spec.ts +++ b/core/src/utils/test/platform.spec.ts @@ -51,6 +51,12 @@ describe('Platform Tests', () => { expect(isPlatform(win, 'hybrid')).toEqual(true); }); + it('should work without win parameter', () => { + (global as any).window = configureBrowser(PlatformConfiguration.DesktopSafari); + expect(isPlatform('capacitor')).toEqual(false); + expect(isPlatform('desktop')).toEqual(true); + }); + it('should return false for "capacitor" and true for "desktop" on desktop safari', () => { const win = configureBrowser(PlatformConfiguration.DesktopSafari); expect(isPlatform(win, 'capacitor')).toEqual(false);