Skip to content

Commit

Permalink
feat(utils): 新增 inMiniProgram
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 22, 2020
1 parent 860f1ba commit 7685872
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/utils/inMiniProgram.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { inMiniProgram } from './inMiniProgram'

const fakeMiniProgramFactory = {
getSystemInfo() {
return {}
},
}

describe('inMiniProgram', () => {
test('表现正常', () => {
expect(inMiniProgram()).toBeFalse()
expect(inMiniProgram('微信')).toBeFalse()
expect(inMiniProgram('百度')).toBeFalse()
expect(inMiniProgram(['微信', '支付宝'])).toBeFalse()
Object.assign(window, {
wx: fakeMiniProgramFactory,
my: fakeMiniProgramFactory,
})
expect(inMiniProgram()).toBeTrue()
expect(inMiniProgram('微信')).toBeTrue()
expect(inMiniProgram('百度')).toBeFalse()
expect(inMiniProgram(['微信', '支付宝'])).toBeTrue()
Object.assign(window, {
swan: fakeMiniProgramFactory,
})
expect(inMiniProgram('百度')).toBeTrue()
})
})
45 changes: 45 additions & 0 deletions src/utils/inMiniProgram.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { castArray } from 'lodash-es'

declare const wx: any
declare const qq: any
declare const my: any
declare const jd: any
declare const swan: any
declare const tt: any
declare const dd: any

const platforms = [
'微信',
'QQ',
'支付宝',
'京东',
'百度',
'字节跳动',
'钉钉',
] as const

export type InMiniProgramPlatform = typeof platforms[number]

const detectors: Record<InMiniProgramPlatform, () => boolean> = {
微信: () => typeof wx !== 'undefined' && !!wx.getSystemInfo,
QQ: () => typeof qq !== 'undefined' && !!qq.getSystemInfo,
支付宝: () => typeof my !== 'undefined' && !!my.getSystemInfo,
京东: () => typeof jd !== 'undefined' && !!jd.getSystemInfo,
百度: () => typeof swan !== 'undefined' && !!swan.getSystemInfo,
字节跳动: () => typeof tt !== 'undefined' && !!tt.getSystemInfo,
钉钉: () => typeof dd !== 'undefined' && !!dd.getSystemInfo,
}

/**
* 检查是否在指定的小程序平台中。
*
* @param platform 指定的小程序平台,若未指定,则表示所有小程序平台
* @returns 返回检查结果
*/
export function inMiniProgram(
platform?: InMiniProgramPlatform | InMiniProgramPlatform[],
): boolean {
return (platform ? castArray(platform) : platforms).some(platform =>
detectors[platform](),
)
}
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export * from './inBrowser'
export * from './inDeno'
export * from './indent'
export * from './inIOS'
export * from './inMiniProgram'
export * from './inNodeJS'
export * from './inWechat'
export * from './isChineseIDCardNumber'
Expand Down

0 comments on commit 7685872

Please sign in to comment.