UNPKG

@bianic-ui/media-query

Version:

A React hook for changing properties or visibility of a component based on css media query

64 lines (53 loc) 1.53 kB
import { isNumber, breakpoints as bps } from "@bianic-ui/utils"; import calculateMeasurement from "calculate-measurement"; /** * Create a media query string from the breakpoints, * using a combination of `min-width` and `max-width`. */ function createMediaQueries(breakpoints) { /** * Get the non-number breakpoint keys from the provided breakpoints */ var keys = Object.keys(breakpoints); /** * Use only the keys matching the official breakpoints names, and sort them in * largest to smallest order */ var sorted = bps.filter(bp => keys.includes(bp)).reverse(); /** * create a min-max media query string */ return sorted.map((breakpoint, index) => { var minWidth = breakpoints[breakpoint]; var next = sorted[index - 1]; var maxWidth = next ? breakpoints[next] : undefined; var query = ""; if (parseInt(minWidth) >= 0) { query = "(min-width: " + toMediaString(minWidth) + ")"; } if (maxWidth) { if (query) { query += " and "; } query += "(max-width: " + toMediaString(subtract(maxWidth)) + ")"; } var mediaQuery = { breakpoint, maxWidth, minWidth, query }; return mediaQuery; }); } function subtract(value) { return calculateMeasurement(value, -0.01); } /** * Convert media query value to string */ function toMediaString(value) { return isNumber(value) ? value + "px" : value; } export default createMediaQueries; //# sourceMappingURL=create-media-query.js.map