a tool for shared writing and social publishing
at main 2.4 kB view raw
1/* 2 * Copyright 2020 Adobe. All rights reserved. 3 * This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. You may obtain a copy 5 * of the License at http://www.apache.org/licenses/LICENSE-2.0 6 * 7 * Unless required by applicable law or agreed to in writing, software distributed under 8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 * OF ANY KIND, either express or implied. See the License for the specific language 10 * governing permissions and limitations under the License. 11 */ 12 13function testUserAgent(re: RegExp) { 14 if (typeof window === "undefined" || window.navigator == null) { 15 return false; 16 } 17 return ( 18 //@ts-ignore 19 window.navigator["userAgentData"]?.brands.some( 20 (brand: { brand: string; version: string }) => re.test(brand.brand), 21 ) || re.test(window.navigator.userAgent) 22 ); 23} 24 25function testPlatform(re: RegExp) { 26 return typeof window !== "undefined" && window.navigator != null 27 ? re.test( 28 //@ts-ignore 29 window.navigator["userAgentData"]?.platform || 30 window.navigator.platform, 31 ) 32 : false; 33} 34 35function cached(fn: () => boolean) { 36 if (process.env.NODE_ENV === "test") { 37 return fn; 38 } 39 40 let res: boolean | null = null; 41 return () => { 42 if (res == null) { 43 res = fn(); 44 } 45 return res; 46 }; 47} 48 49export const isMac = cached(function () { 50 return testPlatform(/^Mac/i); 51}); 52 53export const isIPhone = cached(function () { 54 return testPlatform(/^iPhone/i); 55}); 56 57export const isIPad = cached(function () { 58 return ( 59 testPlatform(/^iPad/i) || 60 // iPadOS 13 lies and says it's a Mac, but we can distinguish by detecting touch support. 61 (isMac() && navigator.maxTouchPoints > 1) 62 ); 63}); 64 65export const isIOS = cached(function () { 66 return isIPhone() || isIPad(); 67}); 68 69export const isAppleDevice = cached(function () { 70 return isMac() || isIOS(); 71}); 72 73export const isWebKit = cached(function () { 74 return testUserAgent(/AppleWebKit/i) && !isChrome(); 75}); 76 77export const isChrome = cached(function () { 78 return testUserAgent(/Chrome/i); 79}); 80 81export const isAndroid = cached(function () { 82 return testUserAgent(/Android/i); 83}); 84 85export const isFirefox = cached(function () { 86 return testUserAgent(/Firefox/i); 87});