Created
September 28, 2025 14:28
-
-
Save philwolstenholme/fff89398fd02f0032859c9a3a60cfc94 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import { UAParser } from "ua-parser-js"; | |
| /** | |
| * Uses the `Sec-CH-UA-Mobile` header if it's available to work out how many | |
| * items to show per page. | |
| */ | |
| export const getItemsPerPage = ({ | |
| astroRequest, | |
| mobileItemsPerPage = 5, | |
| desktopItemsPerPage = 12, | |
| }: { | |
| astroRequest?: Request; | |
| mobileItemsPerPage?: number; | |
| desktopItemsPerPage?: number; | |
| }) => { | |
| if (!astroRequest) { | |
| return desktopItemsPerPage; | |
| } | |
| // Prefer client hints if available. | |
| const clientHintMobile = astroRequest.headers.get("Sec-CH-UA-Mobile"); | |
| if (clientHintMobile) { | |
| return clientHintMobile === "?1" ? mobileItemsPerPage : desktopItemsPerPage; | |
| } | |
| // User agent sniff if we must. | |
| const userAgent = astroRequest.headers.get("User-Agent"); | |
| if (userAgent) { | |
| const { device } = UAParser(userAgent); | |
| const smallScreenDeviceTypes: (typeof device.type)[] = [ | |
| "mobile", | |
| "tablet", | |
| "wearable", | |
| ]; | |
| return smallScreenDeviceTypes.includes(device.type) | |
| ? mobileItemsPerPage | |
| : desktopItemsPerPage; | |
| } | |
| return desktopItemsPerPage; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment