-
Notifications
You must be signed in to change notification settings - Fork 94
/
index.ts
105 lines (85 loc) · 2.34 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import {type Dispatch, useEffect, useState} from 'react';
import {isBrowser} from '../util/const.js';
const queriesMap = new Map<
string,
{mql: MediaQueryList; dispatchers: Set<Dispatch<boolean>>; listener: () => void}
>();
type QueryStateSetter = (matches: boolean) => void;
const createQueryEntry = (query: string) => {
const mql = matchMedia(query);
const dispatchers = new Set<QueryStateSetter>();
const listener = () => {
for (const d of dispatchers) {
d(mql.matches);
}
};
mql.addEventListener('change', listener, {passive: true});
return {
mql,
dispatchers,
listener,
};
};
const querySubscribe = (query: string, setState: QueryStateSetter) => {
let entry = queriesMap.get(query);
if (!entry) {
entry = createQueryEntry(query);
queriesMap.set(query, entry);
}
entry.dispatchers.add(setState);
setState(entry.mql.matches);
};
const queryUnsubscribe = (query: string, setState: QueryStateSetter): void => {
const entry = queriesMap.get(query);
// Else path is impossible to test in normal situation
if (entry) {
const {mql, dispatchers, listener} = entry;
dispatchers.delete(setState);
if (dispatchers.size === 0) {
queriesMap.delete(query);
if (mql.removeEventListener) {
mql.removeEventListener('change', listener);
} else {
// eslint-disable-next-line @typescript-eslint/no-deprecated
mql.removeListener(listener);
}
}
}
};
type UseMediaQueryOptions = {
initializeWithValue?: boolean;
};
/**
* Tracks the state of CSS media query.
*
* @param query CSS media query to track.
* @param options Hook options:
* `initializeWithValue` (default: `true`) - Determine media query match state on first render. Setting
* this to false will make the hook yield `undefined` on first render.
*/
export function useMediaQuery(
query: string,
options: UseMediaQueryOptions = {},
): boolean | undefined {
let {initializeWithValue = true} = options;
if (!isBrowser) {
initializeWithValue = false;
}
const [state, setState] = useState<boolean | undefined>(() => {
if (initializeWithValue) {
let entry = queriesMap.get(query);
if (!entry) {
entry = createQueryEntry(query);
queriesMap.set(query, entry);
}
return entry.mql.matches;
}
});
useEffect(() => {
querySubscribe(query, setState);
return () => {
queryUnsubscribe(query, setState);
};
}, [query]);
return state;
}