Просмотр исходного кода

add touchscreen cond for useIsMobile

reiji-h 1 год назад
Родитель
Сommit
879601298e
1 измененных файлов с 25 добавлено и 4 удалено
  1. 25 4
      apps/app/src/stores/ui.tsx

+ 25 - 4
apps/app/src/stores/ui.tsx

@@ -56,18 +56,39 @@ export const useSidebarScrollerRef = (initialData?: RefObject<HTMLDivElement>):
   return useSWRStatic<RefObject<HTMLDivElement>, Error>('sidebarScrollerRef', initialData);
 };
 
+//
 export const useIsMobile = (): SWRResponse<boolean, Error> => {
   const key = isClient() ? 'isMobile' : null;
 
-  let configuration;
+  let configuration = {
+    fallbackData: false,
+  };
+
   if (isClient()) {
-    const userAgent = window.navigator.userAgent.toLowerCase();
+
+    // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent#mobile_device_detection
+    let hasTouchScreen = false;
+    hasTouchScreen = ('maxTouchPoints' in navigator) ? navigator?.maxTouchPoints > 0 : false;
+
+    if (!hasTouchScreen) {
+      const mQ = matchMedia?.('(pointer:coarse)');
+      if (mQ?.media === '(pointer:coarse)') {
+        hasTouchScreen = !!mQ.matches;
+      }
+      else {
+      // Only as a last resort, fall back to user agent sniffing
+        const UA = navigator.userAgent;
+        hasTouchScreen = /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA)
+      || /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA);
+      }
+    }
+
     configuration = {
-      fallbackData: /iphone|ipad|android/.test(userAgent),
+      fallbackData: hasTouchScreen,
     };
   }
 
-  return useStaticSWR<boolean, Error>(key, undefined, configuration);
+  return useSWRStatic<boolean, Error>(key, undefined, configuration);
 };
 
 export const useIsDeviceLargerThanMd = (): SWRResponse<boolean, Error> => {