-
Notifications
You must be signed in to change notification settings - Fork 95
/
index.ts
45 lines (35 loc) · 1.17 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
import {type MutableRefObject, useEffect, useState} from 'react';
import {off, on} from '../util/misc.js';
export type UsePermissionState = PermissionState | 'not-requested' | 'requested';
/**
* Tracks a permission state.
*
* @param descriptor Permission request descriptor that passed to `navigator.permissions.query`
*/
export function usePermission(descriptor: PermissionDescriptor): UsePermissionState {
const [state, setState] = useState<UsePermissionState>('not-requested');
useEffect(() => {
const unmount: MutableRefObject<(() => void) | null> = {current: null};
setState('requested');
// eslint-disable-next-line @typescript-eslint/no-floating-promises,promise/catch-or-return
navigator.permissions
.query(descriptor)
.then((status): void => {
const handleChange = () => {
setState(status.state);
};
setState(status.state);
on(status, 'change', handleChange, {passive: true});
unmount.current = () => {
off(status, 'change', handleChange);
};
});
return () => {
if (unmount.current) {
unmount.current();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [descriptor.name]);
return state;
}