-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedia-queries.js
46 lines (37 loc) · 1.2 KB
/
media-queries.js
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
/**
* @copyright 2023 Chris Zuber <[email protected]>
*/
import { when } from './dom.js';
export const supported = globalThis.matchMedia instanceof Function;
export function mediaQuery(query = {}) {
console.warn('`mediaQuery()` is deprecated. Please use `matches()` instead.');
return matches(query);
}
export function matches(what = {}) {
return query(what).matches;
}
export function query(query = {}) {
if (! supported) {
return { matches: false, addEventListener: () => null, removeEventListener: () => null };
} else {
const queries = Object.entries(query).map(([k, v]) => `(${k}: ${v})`).join(' and ');
return matchMedia(queries);
}
}
export async function whenMatches(what = {}, { signal } = {}) {
const mq = query(what);
if (! mq.matches) {
await when(mq, 'change', { signal });
}
return mq;
}
export function prefersReducedMotion() {
return matches({ 'prefers-reduced-motion': 'reduce' });
}
export function prefersColorScheme() {
return matches({ 'prefers-color-scheme': 'dark' }) ? 'dark': 'light';
}
export function displayMode() {
const displays = ['browser', 'standalone', 'minimal-ui', 'fullscreen'];
return displays.find(mode => matches({ 'display-mode': mode })) || 'browser';
}