-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathuseFeatureSupported.ts
58 lines (46 loc) · 1.51 KB
/
useFeatureSupported.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
// TODO(2fd): add Docs
import { useEffect, useState } from 'react'
const features = {
Crypto: () => 'crypto' in window,
File: () =>
'File' in window && 'FileList' in window && 'FileReader' in window,
FileSystem: () => 'requestFileSystem' in window,
Notification: () => 'Notification' in window && 'permission' in Notification,
PushManager: () => 'PushManager' in window,
ServiceWorker: () => 'serviceWorker' in navigator,
Share: () => 'share' in navigator,
}
const cache = new Map<keyof typeof features, boolean>()
export default function useFeatureSupported(feature: keyof typeof features) {
const [isSupported, setSupported] = useState(cache.get(feature) || false)
useEffect(() => {
if (!cache.has(feature) && features[feature]) {
cache.set(feature, features[feature]())
}
if (isSupported !== cache.get(feature)) {
setSupported(cache.get(feature)!)
}
}, [])
return isSupported
}
export function useCryptoSupported() {
return useFeatureSupported('Crypto')
}
export function useFileSupported() {
return useFeatureSupported('File')
}
export function useFileSystemSupported() {
return useFeatureSupported('FileSystem')
}
export function useNotificationSupported() {
return useFeatureSupported('Notification')
}
export function usePushManagerSupported() {
return useFeatureSupported('PushManager')
}
export function useServiceWorkerSupported() {
return useFeatureSupported('ServiceWorker')
}
export function useShareSupported() {
return useFeatureSupported('Share')
}