1 | // @mui
|
---|
2 | import { useTheme, Breakpoint } from '@mui/material/styles';
|
---|
3 | import useMediaQuery from '@mui/material/useMediaQuery';
|
---|
4 |
|
---|
5 | // ----------------------------------------------------------------------
|
---|
6 |
|
---|
7 | type ReturnType = boolean;
|
---|
8 |
|
---|
9 | export type Query = 'up' | 'down' | 'between' | 'only';
|
---|
10 |
|
---|
11 | export type Value = Breakpoint | number;
|
---|
12 |
|
---|
13 | export function useResponsive(query: Query, start?: Value, end?: Value): ReturnType {
|
---|
14 | const theme = useTheme();
|
---|
15 |
|
---|
16 | const mediaUp = useMediaQuery(theme.breakpoints.up(start as Value));
|
---|
17 |
|
---|
18 | const mediaDown = useMediaQuery(theme.breakpoints.down(start as Value));
|
---|
19 |
|
---|
20 | const mediaBetween = useMediaQuery(theme.breakpoints.between(start as Value, end as Value));
|
---|
21 |
|
---|
22 | const mediaOnly = useMediaQuery(theme.breakpoints.only(start as Breakpoint));
|
---|
23 |
|
---|
24 | if (query === 'up') {
|
---|
25 | return mediaUp;
|
---|
26 | }
|
---|
27 |
|
---|
28 | if (query === 'down') {
|
---|
29 | return mediaDown;
|
---|
30 | }
|
---|
31 |
|
---|
32 | if (query === 'between') {
|
---|
33 | return mediaBetween;
|
---|
34 | }
|
---|
35 |
|
---|
36 | return mediaOnly;
|
---|
37 | }
|
---|
38 |
|
---|
39 | // ----------------------------------------------------------------------
|
---|
40 |
|
---|
41 | type BreakpointOrNull = Breakpoint | null;
|
---|
42 |
|
---|
43 | export function useWidth() {
|
---|
44 | const theme = useTheme();
|
---|
45 |
|
---|
46 | const keys = [...theme.breakpoints.keys].reverse();
|
---|
47 |
|
---|
48 | return (
|
---|
49 | keys.reduce((output: BreakpointOrNull, key: Breakpoint) => {
|
---|
50 | // eslint-disable-next-line react-hooks/rules-of-hooks
|
---|
51 | const matches = useMediaQuery(theme.breakpoints.up(key));
|
---|
52 |
|
---|
53 | return !output && matches ? key : output;
|
---|
54 | }, null) || 'xs'
|
---|
55 | );
|
---|
56 | }
|
---|