import React, {useContext} from "react"
import {ResponsiveLayoutContext} from "../../components";
/**
* @typedef
*/
type WidthCheckReturn = {
/**
* Whether the screen width is below {@link NARROW_UPPER_BOUND} (exclusive)
*/
wide: boolean
/**
* Whether the screen width is above {@link NARROW_UPPER_BOUND} (inclusive) and below {@link MEDIUM_UPPER_BOUND} (exclusive)
*/
medium: boolean
/**
* Whether the screen width is above {@link MEDIUM_UPPER_BOUND} (inclusive)
*/
narrow: boolean
}
/**
* Width (in pixels) that represents the upper boundary (exclusive) of the `narrow` value.
*
* Until doc auto renders, value is set to `575`
*
* @constant
* @type {number}
* @default
*/
export const NARROW_UPPER_BOUND = 575
/**
* Width (in pixels) that represents the upper boundary (exclusive) of the `medium` value
*
* Until doc auto renders, value is set to `1000`
*
* @constant
* @type {number}
* @default
*/
export const MEDIUM_UPPER_BOUND = 1000
/**
* Custom hook for providing the current app display width in a responsive way.
*
* The hook doesn't take any parameters and returns a set of booleans representing
* the current screen width.
*
* The three returned booleans are: `narrow`, `medium`, `wide`
* - `narrow`: Whether the screen width is below {@link NARROW_UPPER_BOUND} (exclusive)
* - `medium`: Whether the screen width is above {@link NARROW_UPPER_BOUND} (inclusive) and below {@link MEDIUM_UPPER_BOUND} (exclusive)
* - `wide`: Whether the screen width is above {@link MEDIUM_UPPER_BOUND} (inclusive)
*
* ### Hook Usage
*
* #### Checking the current width
* ```
* const {narrow, medium, wide} = useWidthCheck()
*
* ...
*
* if (narrow) {}
* else if (medium) {}
* else if (wide) {}
* ```
*
* It's quick and easy to determine what the current screen width is and display accordingly.
*
* Because they are all booleans, you can also group logic together like:
* ```
* const {narrow, medium, wide} = useWidthCheck()
*
* ...
*
* if (narrow || medium) {}
* ```
*
* @category Hooks
* @module useWidthCheck
* @return {WidthCheckReturn}
*/
export function useWidthCheck() : WidthCheckReturn {
// Load responsive layout context and read current screen width
const responsiveLayout = useContext(ResponsiveLayoutContext)
const width = responsiveLayout.width
let narrow = false
let medium = false
let wide = false
// Check the width vs defined breakpoints
if (width < NARROW_UPPER_BOUND) {
narrow = true
} else if (width < MEDIUM_UPPER_BOUND && width >= NARROW_UPPER_BOUND) {
medium = true
} else if (width >= MEDIUM_UPPER_BOUND) {
wide = true
}
return {wide, medium, narrow}
}
Source