mirror of
https://github.com/ionic-team/ionic-framework.git
synced 2025-11-08 15:51:16 +08:00
refactor(platform): isPlatform() does not need window (#19022)
This commit is contained in:
@ -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);
|
||||
|
||||
|
||||
@ -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);
|
||||
|
||||
Reference in New Issue
Block a user