Last active
January 28, 2022 06:28
-
-
Save maapteh/ef9ba0ae55ce48b0be04250c558b39b8 to your computer and use it in GitHub Desktop.
middleware user agent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// reason: package provided by our components library | |
// eslint-disable-next-line import/no-extraneous-dependencies | |
import MobileDetect from 'mobile-detect'; | |
import { Viewport } from '@lib/types'; | |
/** server-side script for guessing user Viewport if its Mobile/Tablet or others. This initial Viewport is used in our ViewportProvider which then runs the Viewport detection client-side */ | |
export const getViewportFromUserAgent = ( | |
userAgent: string | null | |
): Viewport.lg | Viewport.sm | Viewport.md => { | |
// corporate firewalls or users who like to stay unknown | |
if (!userAgent) { | |
return Viewport.lg; | |
} | |
const device = new MobileDetect(userAgent); | |
const isMobile = device.mobile(); | |
const isTablet = device.tablet(); | |
if (isMobile && !isTablet) { | |
// Our "xs" viewport is given for phones our Tenants do not really support since they are below the 5%, so our best bet is to handle phones like they are sm | |
return Viewport.sm; | |
} | |
if (isTablet) { | |
// we understand they can be rotated etc, once again best educated guess | |
return Viewport.md; | |
} | |
// we handle mobile first | |
return Viewport.sm; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment