Skip to content

Commit

Permalink
feat(utils): add platform utils
Browse files Browse the repository at this point in the history
  • Loading branch information
wangxingkang committed Feb 4, 2024
1 parent bd0fc81 commit 0e10107
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 7 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
"@pansy/classnames": "^1.0.1",
"@pansy/scrollbar-width": "^1.0.0",
"tree-lodash": "^0.3.1",
"type-fest": "^4.9.0"
"type-fest": "^4.9.0",
"user-agent-data-types": "^0.4.2"
},
"devDependencies": {
"@commitlint/cli": "^18.4.4",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export { default as classNames } from '@pansy/classnames';
export { scrollbarWidth } from '@pansy/scrollbar-width';
export * from './rect';
export { isIOS } from './isIOS';
export * from './platform';
export { isBrowser } from './isBrowser';
export { isUrl } from './isUrl';
export { isNil } from './isNil';
Expand Down
5 changes: 0 additions & 5 deletions src/utils/isIOS.ts

This file was deleted.

58 changes: 58 additions & 0 deletions src/utils/platform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/// <reference types="user-agent-data-types" />

function testUserAgent(re: RegExp) {
if (typeof window === 'undefined' || window.navigator == null) {
return false;
}
return (
window.navigator['userAgentData']?.brands.some((brand: { brand: string; version: string }) =>
re.test(brand.brand),
) || re.test(window.navigator.userAgent)
);
}

function testPlatform(re: RegExp) {
return typeof window !== 'undefined' && window.navigator != null
? re.test(window.navigator['userAgentData']?.platform || window.navigator.platform)
: false;
}

export function isMac() {
return testPlatform(/^Mac/i);
}

export function isIPhone() {
return testPlatform(/^iPhone/i);
}

export function isIPad() {
return (
testPlatform(/^iPad/i) ||
// iPadOS 13 lies and says it's a Mac, but we can distinguish by detecting touch support.
(isMac() && navigator.maxTouchPoints > 1)
);
}

export function isAndroid() {
return testUserAgent(/Android/i);
}

export function isIOS() {
return isIPhone() || isIPad();
}

export function isAppleDevice() {
return isMac() || isIOS();
}

export function isWebKit() {
return testUserAgent(/AppleWebKit/i) && !isChrome();
}

export function isChrome() {
return testUserAgent(/Chrome/i);
}

export function isFirefox() {
return testUserAgent(/Firefox/i);
}

0 comments on commit 0e10107

Please sign in to comment.